Search code examples
c++stringdllmql4metatrader4

How to return a string from a C++ DLL into a MetaTrader 4 code-execution ecosystem?


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?


Solution

  • Accidentaly, I put my mind to BOOL APIENTRY DllMain. So it solve my problem without creating threads.

    vector<wchar_t*> tempObjVector;
    
    BOOL APIENTRY DllMain(HMODULE hModule,DWORD  ul_reason_for_call,LPVOID lpReserved)
    {
       switch (ul_reason_for_call)
       {
       case DLL_PROCESS_ATTACH:
       case DLL_THREAD_ATTACH:
       case DLL_THREAD_DETACH:
       case DLL_PROCESS_DETACH: 
           while (tempObjVector.size() != 0)
           {
               delete[] tempObjVector.back();
               tempObjVector.pop_back();
           }
           break;
       }
       return TRUE;
    }
    
    __declspec(dllexport) wchar_t* __stdcall __getJson(wchar_t * listN){
        ....
        ....
        wchar_t* tempObj=new wchar_t[ant.length()+1];
        tempObj[ant.length()] = 0;
        wcscpy(tempObj, constRes);
        tempObjVector.push_back(tempObj);
        return tempObj;
    }