Skip to content

Instantly share code, notes, and snippets.

@davidruhmann
Last active June 25, 2024 13:20
Show Gist options
  • Save davidruhmann/8008844 to your computer and use it in GitHub Desktop.
Save davidruhmann/8008844 to your computer and use it in GitHub Desktop.
[C++] GetCurrentModule - Obtain a Module Handle HMODULE to the current DLL
const HMODULE GetCurrentModuleLegacy()
{
// Query Against Myself
MEMORY_BASIC_INFORMATION mbi = {};
if (0 == VirtualQuery(GetCurrentModuleLegacy, &mbi, sizeof(mbi)))
{
// See GetLastError()
return NULL;
}
return (HMODULE)mbi.AllocationBase;
}
const HMODULE GetCurrentModule()
{
HMODULE hModule = NULL;
// hModule is NULL if GetModuleHandleEx fails.
GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCTSTR)GetCurrentModule, &hModule);
return hModule;
}
const HMODULE GetModuleHandle()
{
// g_hModule set by DllMain
if (NULL == g_hModule)
{
return GetCurrentModule();
}
return g_hModule;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment