How can you get the instance handle of a DLL, if the function that you write is linked into the DLL but you have no access to hInstance
from the DllMain
? GetModuleHandle
only allows you to get the handle to the module that created the current process – in case you don’t know the path to the module (which we assume).
So let’s say you want to somehow get the instance handle but can’t use DllMain
for some reason. The solution is in using VirtualQuery
. We abuse a feature of static variables in PE executables. Unlike the usual stack variable (and various other options), those are located within the loaded image of the DLL. Here’s how it looks.
HMODULE GetMyModuleHandle() { static int s_somevar = 0; MEMORY_BASIC_INFORMATION mbi; if(!::VirtualQuery(&s_somevar, &mbi, sizeof(mbi))) { return NULL; } return static_cast(mbi.AllocationBase); }
If you have linked the CRT of Visual C++, you can get away with a simple reinterpret_cast<HMODULE>(&__ImageBase)
So don’t sweat it, as most people do whenever I quiz them about this
// Oliver