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

廉价感情. 提交于 2021-02-05 09:13:28

问题


I have a Delphi DLL that works when called by delphi apps and exports a method declared as:

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

On the C++ side I have tried:

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

My console error reads:

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

I have built the DLL and the c++ test app using Rad Studio XE4 - it is a 64 bit DLL and APP

How should I have gone about doing this?

Best regards,

garry


回答1:


There is no DllImport in C++. That is for .NET PInvoke instead. So remove that.

The remainder of your C++ function declaration does not match the Delphi function declaration. The correct C++ declaration is as follows:

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

Don't forget to statically link to the DLL's import .LIB file (which you can create using C++Builder's command-line IMPLIB.EXE tool, if needed).

Then, in the app's code, you can call the DLL function like this:

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

Memo1->Lines->Text = aresultstring;

The reason you are getting the conversion error is because the WideString class overrides the & operator to return a pointer to its internal BSTR member. The reason for this is to allow WideString to act like a smart wrapper class for ActiveX/COM strings, eg:

HRESULT __stdcall SomeFuncThatReturnsABStr(BSTR** Output);

WideString output;
SomeFuncThatReturnsABStr(&output);

As such, it is not possible to obtain a pointer to a WideString itself using the & operator. Because of that, the only way (that I know of) to get a real WideString pointer is to dynamically allocate the WideString, eg:

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


来源:https://stackoverflow.com/questions/17303831/how-to-call-delphi-dll-widestring-parameters-from-c-including-var-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!