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

后端 未结 1 507
半阙折子戏
半阙折子戏 2021-01-19 16:42

// delphi code (delphi version : Turbo Delphi Explorer (it\'s Delphi 2006))

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


        
相关标签:
1条回答
  • 2021-01-19 17:07

    The memory for the string is owned by your Delphi code but your p/invoke code will result in the marshaller calling CoTaskMemFree on that memory.

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

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

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

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

    You should also make sure that the calling conventions match by declaring the Delphi function to be stdcall:

    function GetLoginResult: PChar; stdcall;
    

    Although it so happens that this calling convention mis-match doesn't matter for a function that has no parameters and a pointer sized return value.

    In order for all this to work, the Delphi string variable LoginResult has to be a global variable so that its contents are valid after GetLoginResult returns.

    0 讨论(0)
提交回复
热议问题