2

所以我学会了在这种情况下使用 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); 

这很好用。

那么,这个案子呢?

-德尔福代码

 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. 私有静态外部无效登录(IntPtr id,IntPtr pass);// 这种情况下,后面如何使用这个 IntPtr?

  3. 私有静态外部无效登录(字符串ID,字符串传递);

提前致谢。

4

2 回答 2

3

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

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

于 2012-08-13T11:57:43.417 回答
1

您可以使用:Marshal.StringToHGlobalAnsi。http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtohglobalansi.aspx

于 2012-08-12T13:00:48.550 回答