Why does getting the base address using GetModuleHandle work?

c++, winapi

Solution

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.

Problem

``` 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?

Original source