我开发了一个 MFC dll,其中包含一个具有以下原型(prototype)的函数:
//DLL code
long __declspec(dllexport) GetData(CString csIdentifier, CStringArray& arrOfData)
{
//based on the identifier I must add some strings inside the string array
arrOfData.Add("...");
arrOfData.Add("...");
/*.....................*/
return 1;
}
我遇到的问题是在函数被调用之后(从可执行文件)。将调用 arrData 的析构函数并尝试释放内存,但不会成功,因为 arrOfData 的分配是在另一个堆上(在 dll 内)完成的。尽管我使用相同的环境设置编译了两个应用程序(Exe 和 Dll),但在调试和 Release模式下我仍然遇到问题。我该如何解决这个问题?
//Executable code
{
CStringArray arrData;
GetData("Identifier",arrData);
//data is accesible
}
堆冲突发生在代码块之前
最佳答案
为了跨 exe/dll 边界共享 CStringArray 等 MFC 对象,您需要使 DLL 成为 MFC 扩展 DLL。请参阅:https://msdn.microsoft.com/en-us/library/h5f7ck28(v=vs.140).aspx
来自内存管理部分:
MFCx0.dll and all extension DLLs loaded into a client application's address space use the same memory allocator, resource loading, and other MFC global states as if they were in the same application. This is significant because the non-MFC DLL libraries and the regular DLLs do the exact opposite and have each DLL allocating out of its own memory pool.
也有可能您的 DLL 函数需要顶部的 AFX_MANAGE_STATE(AfxGetStaticModuleState()) 以便在外部调用时对环境进行属性设置。
关于c++ - 从 DLL 导出函数释放 CStringArray& 参数时出现堆冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7309277/