在Unicode字符集下,以下代码可用,代码来自网络,修改后增加了个测试函数。在此对代码贡献者表示感谢!
HMODULE GetSelfModuleHandle()
{
MEMORY_BASIC_INFORMATION mbi;
return ((::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0) ? (HMODULE)mbi.AllocationBase : NULL);
}
void TCHAR2Char(const TCHAR* tchar, char* _char)
{
int iLength;
//获取字节长度
iLength = WideCharToMultiByte(CP_ACP, 0, LPCWSTR(tchar), -1, NULL, 0, NULL, NULL);
//将tchar值赋给_char
WideCharToMultiByte(CP_ACP, 0, LPCWSTR(tchar), -1, _char, iLength, NULL, NULL);
}
string GetInstanceFolderPath()
{
string exePath = "";
TCHAR tcFullPath[MAX_PATH];
char* pChPath = new char[MAX_PATH];
memset(pChPath, '\0', MAX_PATH);
/** 获取当前程序的执行路径exe路径 */
GetModuleFileName(GetSelfModuleHandle(),tcFullPath,MAX_PATH);
//GetModuleFileName(NULL, tcFullPath, MAX_PATH);
/** 将tchar转为char */
TCHAR2Char(tcFullPath, pChPath);
exePath = string(pChPath);
string dirPath = "";
size_t iPos = exePath.rfind("\\");
dirPath = exePath.substr(0, iPos);
/** 释放资源 */
delete[] pChPath;
return dirPath;
}
void __declspec(dllexport)__stdcall test4()
{
CString str=GetInstanceFolderPath().c_str();
AfxMessageBox(str);
}
经过上述代码测试后,将函数加入到项目中,结果发现获取的地址是乱码。PS:当时没意识到字符集环境不一样,排查了加密软件、系统语言等等问题后才。。。
没办法只能将上述代码改成多字节字符集适用的。在此过程中稍稍研究了一下多字节字符集和Unicode字符集。详情请见:
HMODULE GetSelfModuleHandle()
{
MEMORY_BASIC_INFORMATION mbi;
return ((::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0) ? (HMODULE)mbi.AllocationBase : NULL);
}
string GetInstanceFolderPath()
{
string exePath = "";
wchar_t tcFullPath[MAX_PATH];
char* pChPath = new char[MAX_PATH];
memset(pChPath, '\0', MAX_PATH);
/** 获取当前程序的执行路径exe路径 */
//GetModuleFileName(NULL, tcFullPath, MAX_PATH);
/*Unicode下使用GetModuleFileNameW,GetModuleFileName是宏定义形式,在Unicode和多字节下 不同*/
GetModuleFileNameW(GetSelfModuleHandle(),tcFullPath,MAX_PATH);
/** 将wchar_t转为char,即Unicode转多字节 */
int iLength;
//获取字节长度
iLength = WideCharToMultiByte(CP_ACP, 0, tcFullPath, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, tcFullPath, -1, pChPath, iLength, NULL, NULL);
exePath = string(pChPath);
string dirPath = "";
size_t iPos = exePath.rfind("\\");
dirPath = exePath.substr(0, iPos);
/** 释放资源 */
delete[] pChPath;
return dirPath;
}
void __declspec(dllexport) __stdcall test4()
{
CString str;
//string s=GetInstanceFolderPath();
str=GetInstanceFolderPath().c_str();
AfxMessageBox(str);
}