i don't work well with C++ but now i need build a function that call Delphi DLL and pass a string to DLL and get return new string.
here is my Delphi DLL code:
library testdll;
uses
System.Classes,Winapi.Windows,System.SysUtils;
{$R *.res}
function hello(name : PWideChar):PWideChar;
var
rs:PWideChar;
begin
rs:=PWideChar('Hello '+rs);
Result:=rs;
end;
exports
hello;
begin
end.
Anyone can help me create simple code in C++ to call and get result form hello function, thank for help.
Update It turns out that Delphi uses a non-standard calling convention for
WideString
return values. So the code below won't work. The basic concept is sound but you need to returnBSTR
or use anout
parameter of typeWideString
. More details here: Why can a WideString not be used as a function return value for interop?Remy's approach is good so long as the caller knows how big a buffer to allocate. An alternative approach is to allocate memory in the DLL and have the caller free the memory. This only works if both parties use the same allocator. An example of a shared allocator is the COM allocator and COM
BSTR
of course uses this. In Delphi aBSTR
maps to WideString which gives us the following approach.Delphi
C++
Obviously in this simple example, the required buffer size for the concatenated string is simple to calculate. But if the actual function in the DLL was more complex then this approach would become more obviously advantageous.
You are trying to concat a PWideChar to a String literal and return it as another PWideChar. That will not work as-is. You should not be returning a PWideChar anyway. That leads to memory management nightmares. A better design is to let the caller pass a buffer into the DLL to fill in instead, eg:
Then, given this C++ declaration::
You can call it all kinds of different ways, depending on your needs:
The same kind of code can be translated to Pascal very easily if you ever need to use the same DLL in Delphi: