Consume DLL made in Delphi 7 in C#

Asked

Viewed 343 times

3

I’m in need of creating a DLL in Delphi 7 and consume it in C#, when the parameters and return are int there are no problems, the problem occurs when I try to use string in return, put in Delphi a Messagedlg and saw that the input parameter is going correctly, in Breakpoint no exception, simply the test console application dies when I make the call.

Delphi:

function Mensagem(texto: string): PAnsiChar; stdcall;
var
  msg: str
begin
  msg := texto;
  Result := PAnsiChar(msg);
end;

exports
  Mensagem;

C#:

[DllImport(@"teste.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
 static extern string Mensagem([MarshalAs(UnmanagedType.AnsiBStr)]string msg);
  • The panel of output should give direction. Already checked what is there shortly after the application die or increase the level of detail to Diagnostic

  • Depending on the parameters I put, it can generate exception, I switched to Shortstring and returned me Managed Debugging Assistant 'Pinvokestackimbalance' 'A call to the Pinvoke function 'Consoleapp1! Consoleapp1.Program::Message' unbalanced the stack. This is probably because the Pinvoke managed signature does not match the unmanaged target signature. Verify that the convention and the Pinvoke signature call parameter are equal to the unmanaged destination signature.

1 answer

3

I found the solution in this post Here

All I had to do was add the Return type and the method I import from the DLL looked like this.

    [return: MarshalAsAttribute(UnmanagedType.AnsiBStr)]
    [DllImport(@"teste.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
    static extern string Mensagem([MarshalAs(UnmanagedType.AnsiBStr)]string msg);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.