I have written a DLL with Delphi and now I need to test a function of this DLL from C++ code.
I've never used C++ before. I installed Code::Blocks and tried to code in C++.
There are no problems with functions that return integers or booleans, but I have problems with functions that return BSTR
type:
error: cannot convert 'GetLastErrText_funtype {aka wchar_t* (__attribute__((__stdcall__)) *)()}' to 'BSTR {aka wchar_t*}' in initialization
Delphi function header:
function GetLastErrText: BSTR; stdcall;
C++ code:
#include <iostream>
#include <cstdlib>
#include <windows.h>
using namespace std;
int main()
{
HINSTANCE dll_module = LoadLibrary("test.dll");
if(dll_module == NULL) { return -1; }
FARPROC GetLastErrText = GetProcAddress(dll_module, "GetLastErrText");
typedef BSTR (__stdcall* GetLastErrText_funtype)();
std::cout << "\nGetLastErrText = " << (void*)GetLastErrText;
if (GetLastErrText != 0) {
BSTR bstr = (GetLastErrText_funtype) GetLastErrText(); // <<<< ERROR
std::cout << "\nstr = " << bstr;
}
FreeLibrary(dll_module);
std::cout << "\n";
return 0;
}
How do I fix this code?
UPDATE (after reading comment of Remy Lebeau):
Very simplified code in Delphi
library test_ws;
uses
System.SysUtils,
Vcl.Dialogs;
function GetLastErrText: WideString; stdcall;
begin
try
Result := 'This is the result of GetLastErrText';
except
on E:Exception do
ShowMessage('Delphi exception::GetLastErrText : ' + E.Message); // when call from C++ code : Out of memory
end;
end;
exports
GetLastErrText;
begin
end.
according code in C++:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HMODULE lib = LoadLibrary("test_ws.dll");
typedef BSTR (__stdcall *Func)();
Func GetLastErrText = (Func) GetProcAddress(lib, "GetLastErrText");
BSTR bstr = GetLastErrText(); // <<<--- Out of memory
std::wcout << bstr;
SysFreeString(bstr);
return 0;
}