3

I have some problems transferring data for delphi imported activeX control in c# environment.


I have a function on delphi side, which takes and returns PChar. I can modify it or do whatever I want with it.

function TActiveFormX.DelphiFunction(S: PChar): PChar;
begin
    ///do something with 'S'
    result:=S;
end;

And on C# side of the program is a function, which calls delphi function, giving it a string parameter to chew on.

public void CSharpFunction()
{
    string a = axActiveFormX1.DelphiFunction("sampleString");
}

I've tested it and apparently everything goes well until C# receives returned PChar. Then whe whole application stops responding and exits. I tried to implement try-catch block to see the Exception message, but the app just crashes before displaying anything.

I suppose it crashes because of variables not being of the same type. Or because of cruel software version mismatch: Delphi 5 + Visual Studio 2012. I googled this, but no luck thus far.

Any help appreciated :)

Martin R
  • 33
  • 3

1 Answers1

1

Your Delphi function isn't designed correctly for interop. If the Delphi function returns a string then you need to agree to use a shared heap so that the callee can allocate the string, and the caller can deallocate it.

The normal way to deal with this is to use COM BSTR, which is wrapped by WideString in Delphi. This uses the shared COM heap so you can allocate in one module and deallocate in another.

It's not possible to use WideString as a return value for interop since Delphi uses a different ABI from the MS tools for return values. This is discussed in more detail here: Why can a WideString not be used as a function return value for interop?

So instead you should return the string via an out parameter:

procedure Foo(const Input: WideString; out Output: WideString);

Your C# type library will be able to import that correctly.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Remember that you have not given any details on how you are importing this Delphi library into your C# code. So I'm working in the dark. I've no idea whether you re-imported the component into the C#. Keep trying. You've still not shown the information I asked for in a comment. Do edit the question to show this. – David Heffernan May 09 '13 at 09:14
  • I compile and build delphi project. Then I use console regsvr command to register dll. Then I open VS and choose delphi component from toolbox. – Martin R May 09 '13 at 09:20
  • So you need to do some debugging. Check that the re-import is working. Add a function with no parameters. Does that become available when you re-import. Then one with integer param. Then one with WideString. And so on. Bracket the problem. – David Heffernan May 09 '13 at 09:24
  • It works :) VS and Delphi just had a bug, so newly created procedures/functions did not show up. I made new projects, freshly registered them, and voila! Thank you big time :) – Martin R May 10 '13 at 08:03