Get pointer to IMAGE_DOS_HEADER with GetModuleHandle?

10,564

Solution 1

This is correct, though if you want the module handle of of a dll you need to specify its path. Otherwise you will get the handle to the process exe. You should also check the returned HMODULE first to see that its valid.

An example of how to get the virtual size of the module:

std::size_t GetModuleSize(const char* szModule)
{
    HMODULE hModule = GetModuleHandle(szModule);
    if(hModule == NULL) return 0;
    IMAGE_DOS_HEADER* pDOSHeader = (IMAGE_DOS_HEADER*)hModule;
    IMAGE_NT_HEADERS* pNTHeaders =(IMAGE_NT_HEADERS*)((BYTE*)pDOSHeader + pDOSHeader->e_lfanew);
    return pNTHeaders->OptionalHeader.SizeOfImage;
}

you'll notice I use IMAGE_DOS_HEADER* and not PIMAGE_DOS_HEADER as I find that more readable and clear.

Solution 2

With Microsoft's compiler and linker, you can use

extern "C" IMAGE_DOS_HEADER __ImageBase;
Share:
10,564
Chris
Author by

Chris

Updated on June 04, 2022

Comments

  • Chris
    Chris almost 2 years

    I am trying to get the image base of my process once it is loaded in memory. From my understanding, you can call GetModuleHandle to get the image base. My question is, does the handle returned essentially point to the IMAGE_DOS_HEADER struct such that you could do the following:

    PIMAGE_DOS_HEADER DosHeader;
    DosHeader = (PIMAGE_DOS_HEADER)GetModuleHandle(NULL);
    

    If this is not correct, what other method could you use?

  • Chris
    Chris almost 13 years
    Thanks Necrolis! I did want to get the base of the module that the code is executing from.
  • user877329
    user877329 almost 10 years
    @Necrolis: MSDN sais "If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file)". So it always returns the module of the process.