Thursday, July 22, 2010

Detecting a HMODULE/HINSTANCE Handle Within the Module You're Running In

Environment: VC++, DLLs

Most DLL developers have faced the challenge of detecting a HMODULE/HINSTANCE handle within the module you're running in. It may be a difficult task if you wrote the DLL without a DLLMain() function or you are unaware of its name. For example:
Your DLL was built without ATL/MFC, so the DLLMain() function exists, but it's hidden from you code and you cannot access the hinstDLL parameter. You do not know the DLL's real file name because it could be renamed by everyone, so GetModuleHandle() is not for you.
This small code can help you solve this problem:


#if _MSC_VER >= 1300 // for VC 7.0
// from ATL 7.0 sources
#ifndef _delayimp_h
extern "C" IMAGE_DOS_HEADER __ImageBase;
#endif
#endif

HMODULE GetCurrentModule()
{
#if _MSC_VER < 1300 // earlier than .NET compiler (VC 6.0)

// Here's a trick that will get you the handle of the module
// you're running in without any a-priori knowledge:
// http://www.dotnet247.com/247reference/msgs/13/65259.aspx

MEMORY_BASIC_INFORMATION mbi;
static int dummy;
VirtualQuery( &dummy, &mbi, sizeof(mbi) );

return reinterpret_cast(mbi.AllocationBase);

#else // VC 7.0

// from ATL 7.0 sources

return reinterpret_cast(&__ImageBase);
#endif
}

No comments:

Post a Comment