Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top