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 .
source share