c++ - 在 Delphi 中实现 C DLL

标签 c++ delphi dll

我正在努力从 C dll 中实现一个函数。它被声明为

int DetectTransactionCode(wchar_t* wi_type, wchar_t* wi_id);

如果在我的 delphi 代码中声明并调用它作为

function DetectTransactionCode (var wi_type, wi_id: PWideChar): Integer;
     cdecl; external 'WiGroupDetect.dll';

procedure TForm20.Button2Click(Sender: TObject);
var witype,wi_id : widestring;
res : integer;
begin
 res := DetectTransactionCode(PWideChar(witype),PWideChar(wi_id));
 showmessage(res.tostring);
 ShowMessage(witype +' & ' +wi_id);
end;

我收到了结果,但是我的 witype 和 wi_id 导致访问冲突。

我也试过:

Function  DetectTransactionCode (var witype,wi_id :widestring ) : Integer cdecl;
                  external 'WiGroupDetect.dll';

procedure TForm20.Button2Click(Sender: TObject);
var witype,wi_id : widestring;
 res : integer;
begin
 res := DetectTransactionCode(witype,wi_id);
 showmessage(res.tostring);
 ShowMessage(witype +' & ' +wi_id);
end;

我假设这两个参数都是输出参数。第 3 方提供了以下内容:

成功返回1,取消/失败返回0

注意:阻塞调用仅在以下情况下返回: 1 - 检测到 wiCode, 2 - 调用 KillDetectionProcess(), 3 – 发生某些错误或故障,或 4 - 最终超时(30 分钟)到期。

参数: wi_type 成功时返回检索到的 token 类型(即 QR 的“WIQR”);或取消/失败时显示“无”。 wi_id 返回成功检测到的 wiCode;取消时显示“已取消”;或有关失败的附加错误信息(即“错误:...”)。

我已经尝试将参数更改为 ansistring、unicodestring,但仍然遇到同样的问题。我怀疑它与 var 参数有关,但不确定如何克服它。如有任何帮助,我们将不胜感激。

他们给了我一个 C 示例实现

[DllImport("WiGroupDetect.dll", EntryPoint = "DetectTransactionCode", CallingConvention =             CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern int DetectTransactionCode([MarshalAsAttribute(UnmanagedType.LPWStr)]  StringBuilder strWITYPE, [MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder strUID);

不确定这是否会改变我的 Delphi 实现

最佳答案

两个参数的类型都是wchar_t*,是指向16位字符的指针。通常这意味着指向以 null 结尾的宽 UTF-16 字符数组的指针。

因此,所提供代码的正确翻译是:

function DetectTransactionCode (wi_type, wi_id: PWideChar): Integer;
    cdecl; external 'WiGroupDetect.dll';

您使用了 WideString 类型的 var 参数。这将匹配指向完全不同的 BSTR 的参数。

我假设 cdecl 调用约定,这是我遇到的每个 C 编译器的默认调用约定。如果您有一些额外的信息表明该函数是 stdcall,那就这样吧。但正如问题中所写,这是 cdecl

不清楚数据的流动方式。两个字符串参数是 in 还是 out?是一进一出吗?如果其中一个是输出参数,那么您需要一些方法来知道要分配多大的缓冲区。该函数不允许您传递缓冲区长度这一事实表明数据流入。也就是说,在这种情况下,参数在 C 代码中应该是 const wchar_t*。这里有很多不确定性。请注意,函数原型(prototype)并未完全定义函数的语义。

关于c++ - 在 Delphi 中实现 C DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26773722/

相关文章:

c++ - g++ 将静态库链接到动态库(不带 -fPIC)

c++ - 创建封装其他 2 个项目的可执行文件

c++ - 在 Visual Studio 中发布版本仍然更慢?

Delphi - Indy TCPServer 如何管理客户端连接?

c# - 使用 DLL 将 C# StringBuilder/string 传递给 C++ char*

c - 如何为 Delphi/Free Pascal/Lazarus DLL 创建 C-Header - 数据类型

c++ - 改进dll丢失错误信息

c++ - 在 C++ 中的多个程序之间本地共享数据(如套接字)

SQL 13 个月的交易和数量数据提取每月分割

delphi - 对于 64 位构建,Trunc() 对于高 Int64 失败