C++設置臨時環境變量,臨時更改PATH路徑

在開發軟件時,碰到了有一大批的dll需要加載,且這些dll中有隱式鏈接到其它dll情況.由於某些原因,不能將dll放入系統目錄中也不能將他們放置在應用程序同一目錄中.

爲集中管理,將其放置到應用程序目錄下的字目錄MyDllPath目錄下.
當使用LoadLibrary加載dll時會由於dll中存在隱式鏈接,且被鏈接的dll不在當前路徑下(在MyDllPath路徑下)而導致加載失敗的情況.
這時,可以使用GetEnvironmentVariable/SetEnvironmentVariable來調整本應用程序的路徑設定.將MyDllPath加載到本應用程序的當前路徑中.這樣即可正常加載所需要的dll了.
如下是修改當前應用程序目錄路徑的方法:
BOOL CDemoApp::SetCurrentEnvPath()  
{  
   char chBuf[0x8000]={0};  
   DWORD dwSize =GetEnvironmentVariable("path",chBuf,0x10000);  
   CString strEnvPaths(chBuf);  
   // 將當前路徑\dll路徑添加到本進程的路徑中  
   if(!::GetModuleFileName(NULL,chBuf,MAX_PATH))  
       return FALSE;  
   CString strAppPath(chBuf);  
   const int nPos = strAppPath.ReverseFind(_T('\\'));  
   if(nPos>0){  
       // 路徑中包含最後的'\\'  
       strAppPath = strAppPath.Mid(0,nPos+1);  
   }  
   strEnvPaths.TrimRight(";");  
   strEnvPaths += ";" + strAppPath +"MyDllPath;";  
   BOOL bRet = SetEnvironmentVariable("path",strEnvPaths);  
   return bRet;  
}  
根據MSDN.應用程序在加載dll時,所搜索的路徑如下(Windows 2000/NT):
The directory from which the application loaded.
The current directory.
The system directory. Use the GetSystemDirectory function to get the path of this directory.
The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章