您的位置:首页 > 编程语言

Windows核心编程学习四:GetModuleHandle获取进程的地址空间中的可执行文件的基地址

2013-04-19 23:40 561 查看
注:源码为学习《Windows核心编程》的一些尝试,非原创。若能有助于一二访客,幸甚。

/*
 * File: DumpModule.cpp
 * Time: 2013-04-19
 * 描述:学习《windows核心编程》
 */

#include <stdio.h>
#include <windows.h>
#include <windowsx.h>
#include <tchar.h>

extern "C" const IMAGE_DOS_HEADER __ImageBase;

/*
	GetModuleHandle Function
	Retrieves a module handle for the specified module. The module must have been loaded by the calling process.
	To avoid the race conditions described in the Remarks section, use the GetModuleHandleEx function.
	HMODULE WINAPI GetModuleHandle(
	  __in_opt  LPCTSTR lpModuleName
	);
	lpModuleName: The name of the loaded module (either a .dll or .exe file). If the file name extension is omitted, 
	the default library extension .dll is appended. The file name string can include a trailing point character (.) to 
	indicate that the module name has no extension. The string does not have to specify a path. When specifying a path, 
	be sure to use backslashes (\), not forward slashes (/). The name is compared (case independently) to the names of 
	modules currently mapped into the address space of the calling process. 
	If this parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).

	If the function succeeds, the return value is a handle to the specified module.
	If the function fails, the return value is NULL. To get extended error information, call GetLastError.
*/
void DumpModule()
{
	// 传递NULL,返回进程的地址空间中的可执行文件的基地址,
	// 若调用GetModuleHandle(NULL)的代码在一个DLL中,返回值仍是可执行文件的基地址,而非DLL文件的基地址
	HMODULE hModule = GetModuleHandle(NULL);
	_tprintf(TEXT("with GetModuleHandle(NULL) = 0x%x\r\n"), hModule);

	// __ImageBase是连接器提供的伪变量,它指向当前正在运行的模块的基地址
	_tprintf(TEXT("with __ImageBase = 0x%x\r\n"), (HINSTANCE)&__ImageBase);

	// 使用DumpModule函数作为参数得到当前模块的基地址
	// 将GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS做第一个参数,会用第二个参数所在DLL的基地址填写第三个参数
	hModule = NULL;
	GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (PCTSTR)DumpModule, &hModule);
	_tprintf(TEXT("with GetModuleHandle(NULL) = 0x%x\r\n"), hModule);
}

int _tmain()
{
	DumpModule();
	return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐