1. 程式人生 > >C++獲取當前模組的路徑(dll/exe)

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()方法。