释放 CStringArray& 时的堆冲突来自 DLL 导出函数的参数

发布于 2024-12-03 04:12:41 字数 665 浏览 1 评论 0原文

我开发了一个 MFC dll,其中包含具有以下原型的函数:

//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),但在调试和发布模式下仍然存在问题。我该如何解决这个问题?

//Executable code
{
    CStringArray arrData;
    GetData("Identifier",arrData);
    //data is accesible
}

堆冲突发生在现有代码块之前

I have developed a MFC dll containing a function having this 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;
}

The problem that I have is after the function gets called (from the executable). The destructor of the arrData will be called and will try to release the memory but it will not succeed because the allocation of the arrOfData was done on another heap(inside the dll). Although I have compiled both applications (Exe and Dll) using the same enviroment settings, I still have the issue in both debug and both release mode. How can I solve the issue?

//Executable code
{
    CStringArray arrData;
    GetData("Identifier",arrData);
    //data is accesible
}

heap violation occurs just before existing the code block

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许仙没带伞 2024-12-10 04:12:41

为了跨 exe/dll 边界共享 MFC 对象(如 CStringArray),您需要使 DLL 成为 MFC 扩展 DLL。请参阅:https://msdn.microsoft.com/ en-us/library/h5f7ck28(v=vs.140).aspx

来自内存管理部分:

MFCx0.dll 和加载到客户端应用程序地址空间中的所有扩展 DLL 使用相同的内存分配器、资源加载和其他 MFC 全局状态,就好像它们位于同一应用程序中一样。这很重要,因为非 MFC DLL 库和常规 DLL 的作用完全相反,并且每个 DLL 都从自己的内存池中分配。

您的 DLL 函数也可能需要顶部的 AFX_MANAGE_STATE(AfxGetStaticModuleState()) 来在外部调用时设置环境属性。

In order to share MFC objects like CStringArray across an exe/dll boundary, you'll need to make the DLL be an MFC Extension DLL. See: https://msdn.microsoft.com/en-us/library/h5f7ck28(v=vs.140).aspx

From the section on Memory Management:

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.

It's also possible that your DLL function needs AFX_MANAGE_STATE(AfxGetStaticModuleState()) at the top to property set up the environment when called externally.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文