【问题标题】:Avoid Resource Conflict避免资源冲突
【发布时间】:2010-06-17 09:36:04
【问题描述】:

我有一个 MFC exe,正在尝试动态加载 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);

MFC exe 和 MFC dll 都有自己的资源文件。

但是,我意识到,如果 MFC exe 和 MFC dll 具有相同的资源 ID,则可能会发生冲突。

// 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);

我可以知道如何避免资源 ID 冲突问题吗? MFC和DLL中可以有两个资源,虽然ID不同,但是相互独立?

这意味着,DLL 只会加载 DLL 的资源。 EXE 只会加载 EXE 的资源。

【问题讨论】:

    标签: c++ mfc


    【解决方案1】:

    您需要为自己保留跟踪句柄,该句柄将在 dllmain 期间传入。

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

    那么当你想引用本地资源(即LoadString)时,传递dll句柄

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

    【讨论】:

      【解决方案2】:

      尝试在 MFC DLL 中使用 AfxGetInstanceHandle() 以获取 DLL 的 HINSTANCE。然后传给CString::LoadString()

      /* Code in MFC DLL. */
      
      CString s;
      // Load resource 101 in the DLL.
      s.LoadString(AfxGetInstanceHandle(), 101); 
      AfxMessageBox(s); 
      

      【讨论】:

      • AfxGetInstanceHandle() 在可以使用 MFC 时是很好的解决方案。
      • 我提到了AfxGetInstanceHandle(),因为 OP 正在使用 MFC DLL。否则,我会选择您的 DllMain 解决方案。
      • 我试过了,AfxGetInstanceHandle() 将返回 EXE 句柄,而不是 DLL。然而 YeenFei 的解决方案是有效的。
      • 对于常规 DLL(有或没有 MFC 链接),AfxGetInstanceHandle 将返回 DLL 本身。对于 MFC 扩展 DLL,AfxGetInstanceHandle 将返回 EXE 本身。
      猜你喜欢
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      相关资源
      最近更新 更多