Alex Rivera | Logout

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

Asked 2009-02-17T14:33:58.280
40

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

Edit
Report

1 Answer

33

__ImageBase is a linker generated symbol that is the DOS header of the module (MSVC only). From that you can cast its address to an HINSTANCE or HMODULE. So it's more convenient than going through an API.

So you just need to do this:

EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase)

From https://web.archive.org/web/20100123173405/http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx

answered 2009-02-17T17:28:00.607

Your Answer