C++获取当前模块的路径(dll/exe)

最近整理了一些获取当前模块路径的代码,都是通过调用 GetModuleFileName() 来获取


DWORD WINAPI GetModuleFileName(
    _In_opt_  HMODULE hModule,
    _Out_     LPTSTR lpFilename,
    _In_      DWORD nSize
);


hModule

[in] Handle to the module whose executable file name is being requested.

If this parameter is NULL, GetModuleFileName returns the path for the file used to create the calling process.

lpFilename

[out] Pointer to a buffer that is filled in with the path and file name of the module.

nSize

[in] Specifies the length, in characters, of the lpFilename buffer.

If the length of the path and file name exceeds this limit, the string is truncated.


第一种:

	char	szBuff[MAX_PATH] = {0};
	HMODULE hModuleInstance = _AtlBaseModule.GetModuleInstance();
	GetModuleFileNameA(hModuleInstance,szBuff, MAX_PATH);
	CString strTmp = CA2T(szBuff);
	m_strExePath = strTmp.Mid(0, strTmp.ReverseFind('\\'));

适用于获取dll、exe路径,可在console、MFC、ATL工程中使用。


第二种:

<pre name="code" class="cpp">        char szBuff[MAX_PATH] = {0};
GetModuleFileName(AfxGetStaticModuleState()->m_hCurrentInstanceHandle, szBuff ,MAX_PATH);

 适用于获取dll、exe路径,可在MFC、ATL工程中使用,不能再console中使用。 


第三种:

<span style="white-space:pre">	</span>GetModuleFileName((HMODULE)&__ImageBase, szFull, _MAX_PATH);

适用于获取dll、exe路径,可在MFC、ATL工程中使用,不能再console中使用。



最后插一句CString的GetBuffer():

 对一个CString变量,你可以使用的唯一合法转换符是LPCTSTR,直接转换成非常量指针(LPTSTR-[const] char*)是错误的。正确的得到一个指向缓冲区的非常量指针的方法是调用GetBuffer()方法。



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值