I have a static library that may get linked into either a .exe
or a .dll
. At runtime I want one of my library functions to get the HMODULE
for whatever thing the static library code has been linked into.
I currently use the following trick (inspired from this forum):
const HMODULE GetCurrentModule() { MEMORY_BASIC_INFORMATION mbi = {0}; ::VirtualQuery( GetCurrentModule, &mbi, sizeof(mbi) ); return reinterpret_cast<HMODULE>(mbi.AllocationBase); }
Is there a better way to do this that doesn't look so hacky?
(Note: The purpose of this is to load some Win32 resources that I know my users will have linked in at the same time as my static library.)
HMODULE. A handle to a module. The is the base address of the module in memory. HMODULE and HINSTANCE are the same in current versions of Windows, but represented different things in 16-bit Windows.
'Ctrl+F' to find Handle or DLL.
The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. However, if this handle is passed to the FreeLibrary function, the reference count of the mapped module will be decremented.
hInstance is something called a "handle to an instance" or "handle to a module." The operating system uses this value to identify the executable (EXE) when it is loaded in memory. The instance handle is needed for certain Windows functions—for example, to load icons or bitmaps.
HMODULE GetCurrentModule() { // NB: XP+ solution! HMODULE hModule = NULL; GetModuleHandleEx( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)GetCurrentModule, &hModule); return hModule; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With