C++獲取當前模塊的路徑(dll/exe)


最近整理了一些獲取當前模塊路徑的代碼,都是通過調用 GetModuleFileName() 來獲取


  1. DWORD WINAPI GetModuleFileName(  
  2.     _In_opt_  HMODULE hModule,  
  3.     _Out_     LPTSTR lpFilename,  
  4.     _In_      DWORD nSize  
  5. );  


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.

 

第一種:

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

適用於獲取dll、exe路徑,可在console、MFC、ATL工程中使用。


第二種:

  1. <pre name="code" class="cpp">        char szBuff[MAX_PATH] = {0};  

GetModuleFileName(AfxGetStaticModuleState()->m_hCurrentInstanceHandle,szBuff,MAX_PATH);
適用於獲取dll、exe路徑,可在MFC、ATL工程中使用,不能再console中使用。

第三種:

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



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM