【问题标题】:How to pass c# string to delphi .dll PChar type?如何将 c# 字符串传递给 delphi .dll PChar 类型?
【发布时间】:2012-08-08 23:03:05
【问题描述】:

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

 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);

提前致谢。

【问题讨论】:

  • 什么delphi版本?由于这主要是一个 C# 问题,如果底层 DLL 是 delphi 7 dll,或 XE那么您上面列出的签名将有两种不同的含义。

标签: c# delphi pinvoke delphi-2006


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    【讨论】:

    • 虽然您可以这样做,但您必须在完成后释放 HGlobal。让 p/invoke marshaller 更容易为您完成工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多