本文介绍了如何将字符串从C ++ DLL返回到MetaTrader 4代码执行生态系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能

__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;
}

此DLL返回 wchar_t * 到MetaTrader4。

This DLL returns wchar_t* to MetaTrader4.

我尝试了很多方法来返回正确的值并避免内存泄漏,例如设置返回类型 const wchar_t * ,使用 delete [] 的析构函数创建我自己的类。但是所有这些尝试均未成功:我得到了'?? ello'而不是'hello'。仅前一个或两个符号不正确。创建 thread 可以正常工作。但是,我想知道,是否有更好的解决方案?

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?

推荐答案

偶然的是,我将注意力放在 BOOL APIENTRY DllMain 。因此,它无需创建线程即可解决我的问题。

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

这篇关于如何将字符串从C ++ DLL返回到MetaTrader 4代码执行生态系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:48