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

注:源码为学习《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;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值