tags:

views:

29

answers:

2

I have a MFC exe, trying to dynamic load a MFC dll.

// This is code in MFC exe
HINSTANCE h = AfxLoadLibrary(_T("DLL.dll"));
typedef void(*FUN)();
FUN fun = (FUN)GetProcAddress(h, "loveme");
FreeLibrary(h);

Both MFC exe and MFC dll, are having their own resource file.

However, I realize that, if MFC exe and MFC dll are having a same resource ID, conflict may occur.

// This is code in MFC dll. Both exe and dll, are having resources with
// ID 101.
CString s;
s.LoadString(101);
// Resource 101 in exe is being shown :(
AfxMessageBox(s);

May I know how I can avoid resource ID conflict problem? Can we have two resource in both MFC and DLL, although their ID is different, but they are independent from each other?

This means, DLL will only load DLL's resource. EXE will only load EXE's resource.

A: 

Try using AfxGetInstanceHandle() in the MFC DLL to get an HINSTANCE to the DLL. Then pass it to CString::LoadString():

/* Code in MFC DLL. */

CString s;
// Load resource 101 in the DLL.
s.LoadString(AfxGetInstanceHandle(), 101); 
AfxMessageBox(s); 
In silico
AfxGetInstanceHandle() is good solution when MFC can be used.
YeenFei
I mentioned `AfxGetInstanceHandle()` because the OP is using an MFC DLL. Otherwise, I would go for your `DllMain` solution.
In silico
I had tried out, AfxGetInstanceHandle() will return EXE handle, not DLL. YeenFei's solution works however.
Yan Cheng CHEOK
For regular DLL (with or without MFC linking), AfxGetInstanceHandle will return DLL itself. For MFC extension DLL, AfxGetInstanceHandle will return EXE itself.
Yan Cheng CHEOK
+2  A: 

You will need to keep track handle to yourself, which will be passed in during dllmain.

HINSTANCE hDLLInstance = 0;

extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
    hDLLInstance = hInstance;
    ...
}

then when you want to refer to local resources (ie. LoadString), pass the dll handle

...
CString s; 
s.LoadString(hDLLInstance, 101); 
AfxMessageBox(s); 
...
YeenFei