Get HModule from inside a DLL

前端 未结 3 896
挽巷
挽巷 2021-01-19 05:43

I need to load some resource from my DLL (i need to load them from the DLL code), for doing that I\'m using FindResource.

To do that i need the HModule of the DLL.

相关标签:
3条回答
  • 2021-01-19 05:50

    Depending upon how your software is architected, you may not have access to DllMain or the code that wants the resource may not even know it's inside a DLL or exe!

    The DLLMain function is given the DLL's module handle. Store it in a globally accessible variable.

    Or, lookup the module based upon a function known to the local code:

    // Determine the module handle by locating a function
    // you know resides in that DLL or exe
    HMODULE hModule;
    GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
                       GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                       (LPCSTR)&myDLLfuncName, &hModule);
    
    HRSRC hRscr = FindResource(hModule, ............);
    
    0 讨论(0)
  • 2021-01-19 05:53

    You get it from the DllMain() entrypoint, 1st argument. Write one, store it in a global variable:

    HMODULE DllHandle;
    
    BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) {
      if (dwReason == DLL_PROCESS_ATTACH) DllHandle = hModule;
      return TRUE;
    }
    

    There's an undocumented hack that works on any version of 32-bit and 64-bit Windows that I've seen. The HMODULE of a DLL is the same value as the module's base address:

    static HMODULE GetThisDllHandle()
    {
      MEMORY_BASIC_INFORMATION info;
      size_t len = VirtualQueryEx(GetCurrentProcess(), (void*)GetThisDllHandle, &info, sizeof(info));
      assert(len == sizeof(info));
      return len ? (HMODULE)info.AllocationBase : NULL;
    }
    
    0 讨论(0)
  • 2021-01-19 06:13

    The first argument to DllMain() is the HMODULE of the DLL.

    0 讨论(0)
提交回复
热议问题