堆释放CStringArray&参数从DLL导出函数 [英] Heap Violations when releasing a CStringArray& parameter from a DLL exported function

查看:417
本文介绍了堆释放CStringArray&参数从DLL导出函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个包含具有这个原型的函数的MFC dll:

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

我遇到的问题是函数调用后(从可执行文件) 。 arrData的析构函数将被调用,并将尝试释放内存,但它不会成功,因为 arrOfData 的分配是在另一个堆(dll内部)上完成的。虽然我已经编译了两个应用程序(Exe和Dll)使用相同的环境设置,我仍然有调试和两个释放模式的问题。如何解决此问题?

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
}

代码块

推荐答案

为了在exe / dll边界上共享像CStringArray这样的MFC对象,是一个MFC扩展DLL。请参阅: https://msdn.microsoft.com/ en-us / library / h5f7ck28(v = vs.140).aspx

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

从内存管理部分:


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

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())在顶部to属性设置外部调用环境。

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.

这篇关于堆释放CStringArray&参数从DLL导出函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆