I have following function
__declspec(dllexport) wchar_t* __stdcall __getJson(wchar_t * listN){
setlocale(LC_ALL, "");
//function logic
wstring ant = utf8_to_wstring(result);
const WCHAR* constRes = ant.c_str();
WCHAR* tempObj=new WCHAR[ant.length()];
wcscpy(tempObj, constRes);
thread Thread([tempObj]{
Sleep(1000);
delete[] tempObj;
});
Thread.detach();
return tempObj;
}
This DLL returns wchar_t*
to MetaTrader4.
I tried many ways to return correct value and avoid memory leaks such as set return type const wchar_t*
, creating my own class with destructor with delete[]
in. But all this attempts was unsuccessful: I got '??ello'
instead of 'hello'
. Just first one or two symbols were incorrect. With creating thread
it works right. But, I want to know, may there be better solution?
#ol' ASM hackers always used to start with
#assume nothing ; mql4_string != string
Bingo, the headbang is evident. Receiving side does not assume, since New-
MQL4.56789
was introduced, it's representation of a block of bytes as astring
, but astruct
(!).To create a string in your DLL and pass it to the caller, you must dynamically allocate some memory in the DLL to store the string's characters, and pass a pointer to that memory to the caller.
Moreover, the caller must be able to release that memory when the string is not needed anymore.
To make it work properly, you must use the same memory manager/allocator to both allocate and free the string's memory.
One option would be to use a common system-wide allocator like the COM allocator. In this way, you can allocate the memory in the DLL using
CoTaskMemAlloc
, and the caller can free it using the matchingCoTaskMemFree
.Another option would be to return a
BSTR
string, allocated withSysAllocString
in the DLL. And the caller would release that string invokingSysFreeString
.Or, you could provide a custom function to free the string's memory in your DLL. For example, you could allocate the string's memory in your DLL using
new[]
, and you could provide aMyDllFreeString
function that invokesdelete[]
.Note that, when you allocate memory for a C-style string, you must consider an additional slot for the string's NUL-terminator (so, you must allocate
stringLength + 1
wchar_t
s).Accidentaly, I put my mind to
BOOL APIENTRY DllMain
. So it solve my problem without creating threads.Another way of doing that (a little bit simpler, but for some cases only):