Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the HMODULE for the currently executing code?

Tags:

c++

c

winapi

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.)

like image 563
pauldoo Avatar asked Feb 17 '09 14:02

pauldoo


People also ask

What is an HMODULE?

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.

How do I get a DLL handle?

'Ctrl+F' to find Handle or DLL.

What is GetModuleHandle?

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.

What is HINSTANCE?

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.


1 Answers

HMODULE GetCurrentModule() { // NB: XP+ solution!   HMODULE hModule = NULL;   GetModuleHandleEx(     GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,     (LPCTSTR)GetCurrentModule,     &hModule);    return hModule; } 
like image 158
Serge Wautier Avatar answered Oct 02 '22 09:10

Serge Wautier