如何从C++调用Delphi DLL WideString参数(包括var参数)

How to call Delphi DLL WideString Parameters from C++ (including var parameters)

本文关键字:参数 包括 var WideString DLL C++ 调用 Delphi      更新时间:2023-10-16

我有一个Delphi DLL,当被Delphi应用程序调用时可以工作,并导出一个声明为:的方法

Procedure ProduceOutput(request,inputs:widestring; var ResultString:widestring);stdcall;

在C++方面,我尝试过:

[DllImport( "ArgumentLab.dll", CallingConvention = CallingConvention.StdCall, CharSet=CharSet.WideString )];
 extern void ProduceOutput(WideString request, WideString inputs, WideString ResultString);
WideString arequest = WideString(ComboBox1->Text);
WideString ainput = "<xml> Input Text Goes Here </XML>";
WideString  aresultstring;
WideString &aresultstringpointer = aresultstring;
aresultstring = " ";
ProduceOutput(arequest, ainput, &aresultstringpointer);
Memo1->Lines->Text = aresultstring;

我的控制台错误显示:

 Unit1.cpp(13): candidate function not viable: no known conversion from 'BSTR *' (aka 'wchar_t **') to 'System::WideString' for 3rd argument;

我已经使用Rad Studio XE4构建了DLL和c++测试应用程序-它是一个64位DLL和应用程序

我该怎么做呢?

致问候,

garry

C++中没有DllImport。这是针对.NET PInvoke的。所以把它去掉。

C++函数声明的其余部分与Delphi函数声明不匹配。正确的C++声明如下:

void __stdcall ProduceOutput(WideString request, WideString inputs, WideString &ResultString);

不要忘记静态链接到DLL的import.LIB文件(如果需要,可以使用C++Builder的命令行IMPLIB.EXE工具创建)。

然后,在应用程序的代码中,你可以像这样调用DLL函数:

WideString arequest = ComboBox1->Text;
WideString ainput = "<xml> Input Text Goes Here </XML>";
WideString aresultstring;
ProduceOutput(arequest, ainput, aresultstring);
Memo1->Lines->Text = aresultstring;

出现转换错误的原因是WideString类重写&运算符以返回指向其内部BSTR成员的指针。这样做的原因是允许WideString充当ActiveX/COM字符串的智能包装类,例如:

HRESULT __stdcall SomeFuncThatReturnsABStr(BSTR** Output);

WideString output;
SomeFuncThatReturnsABStr(&output);

因此,使用&运算符不可能获得指向WideString本身的指针。因此,(据我所知)获得真正的WideString指针的唯一方法是动态分配WideString,例如:

WideString *pStr = new WideString;
...
delete pStr;