c++ - 从 DLL 导出函数释放 CStringArray& 参数时出现堆冲突

标签 c++ windows dll heap-memory dllexport

我开发了一个 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/

相关文章:

c++ - 复制构造函数是可行的重载吗?

c++ - GDB 断点在 asio socket->connect 调用后停止工作

windows - DOSKEY 别名在批处理脚本中不起作用 (Windows 7)

c++ - 缺少 msvcr80.dll

java - jni 程序中 dll 的保存位置

c++ - 在不复制的情况下将 unique_ptr 的数据释放并转换为另一个

c++ - 对于 `shared_ptr` 树结构,比 "widget"更好的选择?

windows - 诸如logcat之类的任何类型的软件都可以在Windows Xp os中查看错误日志

windows - ffmpeg的python调用错过了目标文件参数

c++ - Ruby - 将方法作为回调传递给 DLL 库