windows 使用 GetModuleHandle 获取指向 IMAGE_DOS_HEADER 的指针?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6126980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get pointer to IMAGE_DOS_HEADER with GetModuleHandle?
提问by Chris
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:
一旦我的进程加载到内存中,我就会尝试获取它的图像库。根据我的理解,您可以调用 GetModuleHandle 来获取图像库。我的问题是,返回的句柄是否本质上指向 IMAGE_DOS_HEADER 结构,以便您可以执行以下操作:
PIMAGE_DOS_HEADER DosHeader;
DosHeader = (PIMAGE_DOS_HEADER)GetModuleHandle(NULL);
If this is not correct, what other method could you use?
如果这不正确,您还可以使用什么其他方法?
回答by Necrolis
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.
这是正确的,但如果您想要 dll 的模块句柄,则需要指定其路径。否则,您将获得进程 exe 的句柄。您还应该先检查返回的内容是否HMODULE
有效。
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.
你会注意到我使用IMAGE_DOS_HEADER*
而不是PIMAGE_DOS_HEADER
因为我发现它更易读和清晰。
回答by user9004592
With Microsoft's compiler and linker, you can use
使用 Microsoft 的编译器和链接器,您可以使用
extern "C" IMAGE_DOS_HEADER __ImageBase;