在开发软件时,碰到了有一大批的dll需要加载,且这些dll中有隐式链接到其它dll情况.由于某些原因,不能将dll放入系统目录中也不能将他们放置在应用程序同一目录中.
C++设置临时环境变量,临时更改PATH路径
精选 转载为集中管理,将其放置到应用程序目录下的字目录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.
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Linux环境变量配置全攻略
Linux环境变量配置;Linux读取环境变量;Linux环境变量配置方法.......
bash 环境变量 vim linux rhce -
C++成员变量初始化
class Judgement{public: Judgement():nMaxM(8),nMaxN(3) { //nMaxM = 8;
C++ 职场 休闲 const 成员变量 -
C++ GDI+环境的初始化
详细介绍使用gdi+时,需要做的准备工作。
图像处理 gdi+ 初始化 应用程序 -
C++成员变量的初始化顺序
C++成员变量的初始化顺序
C++ 成员变量 初始化顺序 初始化 静态变量 -
C++初始化列表
C++初始化列表详解
C++ 初始化列表 -
java 临时环境变量 linux临时环境变量
查看当前环境变量
环境变量 全局变量 bash