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 :)
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.