Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HModule from inside a DLL

Tags:

c++

resources

dll

I need to load some resource from my DLL (i need to load them from the DLL code), for doing that I'm using FindResource.

To do that i need the HModule of the DLL. How to find that?

(I do not know the name (filename) of the DLL (the user can change it))

like image 980
feal87 Avatar asked Nov 27 '22 23:11

feal87


2 Answers

You get it from the DllMain() entrypoint, 1st argument. Write one, store it in a global variable:

HMODULE DllHandle;

BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) {
  if (dwReason == DLL_PROCESS_ATTACH) DllHandle = hModule;
  return TRUE;
}

There's an undocumented hack that works on any version of 32-bit and 64-bit Windows that I've seen. The HMODULE of a DLL is the same value as the module's base address:

static HMODULE GetThisDllHandle()
{
  MEMORY_BASIC_INFORMATION info;
  size_t len = VirtualQueryEx(GetCurrentProcess(), (void*)GetThisDllHandle, &info, sizeof(info));
  assert(len == sizeof(info));
  return len ? (HMODULE)info.AllocationBase : NULL;
}
like image 63
Hans Passant Avatar answered Dec 04 '22 22:12

Hans Passant


The first argument to DllMain() is the HMODULE of the DLL.

like image 27
Ignacio Vazquez-Abrams Avatar answered Dec 04 '22 21:12

Ignacio Vazquez-Abrams