gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:05:01 25 4
gpt4 key购买 nike

所以我学会了在这种情况下使用 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 在 () 里面。那么将字符串值传递给该登录 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);

提前致谢。

最佳答案

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

您的选项 1 也适用,但不必要地冗长,因为您只是重新声明默认编码。选项 2 也可以工作,但你只会为自己创造额外的工作。您有责任在 native 函数调用返回后释放 IntPtr 值。

关于c# - 如何将 c# 字符串传递给 delphi .dll PChar 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11922074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com