问题
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. How to find that?
(I do not know the name (filename) of the DLL (the user can change it))
回答1:
The first argument to DllMain() is the HMODULE
of the DLL.
回答2:
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;
}
回答3:
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, ............);
来源:https://stackoverflow.com/questions/2396328/get-hmodule-from-inside-a-dll