Accessing the current module’s HINSTANCE from a static library

Raymond Chen

If you’re writing a static library, you may have need to access the HINSTANCE of the module that you have been linked into. You could require that the module that links you in pass the HINSTANCE to a special initialization function, but odds are that people will forget to do this.

If you are using a Microsoft linker, you can take advantage of a pseudovariable which the linker provides.

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

The pseudovariable __ImageBase represents the DOS header of the module, which happens to be what a Win32 module begins with. In other words, it’s the base address of the module. And the module base address is the same as its HINSTANCE.

So there’s your HINSTANCE.

[Raymond is currently on vacation; this message was pre-recorded.]

0 comments

Discussion is closed.

Feedback usabilla icon