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