How to call this function delphi.dll from c #?

// delphi code (delphi version: Turbo Delphi Explorer (this is Delphi 2006))

function GetLoginResult:PChar; begin result:=PChar(LoginResult); end; 

// C # code to use the above delphi function (I use unity 3d, inside, C #)

 [DllImport ("ServerTool")] private static extern string GetLoginResult(); // this does not work (make crash unity editor) [DllImport ("ServerTool")] [MarshalAs(UnmanagedType.LPStr)] private static extern string GetLoginResult(); // this also occur errors 

What is the correct way to use this feature in C #?

(for use also in delphi, the code is similar if (event = 1) and (tag = 10), then writeln ("Logon Result:", GetLoginResult);)

+4
source share
1 answer

The memory for the string belongs to your Delphi code, but your p / invoke code will cause the CoTaskMemFree to call CoTaskMemFree in that memory.

What you need to do is tell the marshaller that he should not take responsibility for freeing the memory.

 [DllImport ("ServerTool")] private static extern IntPtr GetLoginResult(); 

Then use Marshal.PtrToStringAnsi() to convert the return value to a C # string.

 IntPtr str = GetLoginResult(); string loginResult = Marshal.PtrToStringAnsi(str); 

You must also ensure that the calling conventions match by declaring the Delphi stdcall function:

 function GetLoginResult: PChar; stdcall; 

Although it happens that this incorrect call coincidence does not matter for a function that has no parameters, and a return value for the size of the pointer.

For this to work, the Delphi LoginResult string variable must be a global variable so that its contents are correct after GetLoginResult .

+8
source

All Articles