3
DWORD baseAddress = (DWORD) GetModuleHandle(NULL);

If I put that code into a DLL and inject it to a process, that seems to equal the base address of the injected process.

How does that work exactly? How does the cast from HMODULE to DWORD work? Would it work if I cast it to void* instead of DWORD?

user2654180
  • 73
  • 1
  • 3

2 Answers2

5

This is an implementation detail of the 32-bit and 64-bit version of Windows. HMODULE is older than that, in the 16-bit version of Windows they were true handles. That was not necessary anymore in win32, the virtual memory address at which a module is loaded uniquely identifies the module. So using the VM address was preferable, no need to keep it in a handle table.

This does mean that you can't cast to DWORD, not good enough to store a virtual memory address on the 64-bit version. You'll need to use DWORD_PTR.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
3

It works because Windows just happened to use the base address as an identifying handle, and because on a 32-bit system an address fits into a DWORD. Since Windows isn't required to do that, you shouldn't rely on it for anything.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622