如何将c#字符串传递给delphi .dll PChar类型?

时间:2012-08-12 12:16:27

标签: c# delphi pinvoke delphi-2006

所以我在这种情况下学会了使用IntPtr,

-delphi(delphi 2006版)代码

 function GetRequestResult(out code:integer):PChar; stdcall;
   begin
    LogMessage('GetRequestResult');
    code:=requestCode;
    result:=PChar(RequestResult);
    LogMessage('GetRequestResult done');
   end;

然后,在c#中使用, 我喜欢,

IntPtr str = GetRequestResult(out code); 
string loginResult = Marshal.PtrToStringAnsi(str); 

这很有效。

然后,这个案子怎么样?

-delphi code

 procedure Login(login,password:PChar); stdcall;
...
...

这个PChar在里面()。 那么将字符串值传递给Login delphi函数的确切方法是什么?

[DllImport(“ServerTool”)]

  1. private static extern void Login([MarshalAs(UnmanagedType.LPStr)] string id,[MarshalAs(UnmanagedType.LPStr)] string pass);

  2. private static extern void Login(IntPtr id,IntPtr pass); //在这种情况下,如何在后期使用此IntPtr?

  3. private static extern void Login(string id,string pass);

  4. 提前致谢。

2 个答案:

答案 0 :(得分:3)

您的选项3是执行此操作的正确方法。 p / invoke marshaller将C#字符串映射到指向空终止字符数组的指针,即PChar。默认调用约定是stdcall,默认字符集是Ansi,因此您不需要指定它们。

您的选项1也有效,但由于您只是重新声明默认的编组,因此不必要地冗长。选项2也可以工作,但你只是为自己创造额外的工作。一旦返回本机函数调用,您就有责任释放IntPtr值。

答案 1 :(得分:1)

相关问题