Qt5.9.9+VS2017设置多字节字符集后仍遇字符转换错误求助
Qt5.9.9 + VS2017 字符集编译错误解决方案
我在Qt5.9.9搭配VS2017的开发环境中遇到字符集相关编译错误,已将项目字符集设置为“使用多字节字符集”但无效,相同代码在控制台程序中设置该字符集即可正常运行。相关代码及错误如下:
第一段代码及错误
代码
CDllLoader::Load(const char* Dll, bool* pLoadError /*=NULL*/) { // load the dll m_hDLL = LoadLibrary(Dll); }
编译错误
Cannot convert parameter 1 from “const char *” to “LPCWSTR” ...\dllloader.cpp 68
第二段代码及错误
代码
CDllLoader::HandleFatalError(const char* Dll) { // create a buffer for the error-message LPVOID lpMsgBuf; // create the message text FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); // copy the error-message in a string std::string Text((LPCTSTR)lpMsgBuf);//Corresponding to row 185 // free's the error-message-buffer LocalFree(lpMsgBuf); // add the dll-name to the error-string Text += Dll; // exit the application with a error-messagebox FatalAppExit(0, Text.c_str());//Corresponding to row 191 }
编译错误
Error C2664 “std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string(const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)”: Cannot convert parameter 1 from “LPCTSTR” to “std::initializer_list<_Elem>” micro_epsilon1 d:\code_rela\micro_epsilon1\micro_epsilon1\dllloader.cpp 185
Error C2664 “void FatalAppExitW(UINT,LPCWSTR)”: Cannot convert parameter 2 from“const _Elem *” to “LPCWSTR” micro_epsilon1 d:\code_rela\micro_epsilon1\micro_epsilon1\dllloader.cpp 191
解决方案
1. 确认Qt项目字符集设置是否被qmake覆盖
Qt项目的VS字符集设置可能被.pro文件的配置覆盖:
- 打开项目的
.pro文件,检查是否存在DEFINES += UNICODE或DEFINES += _UNICODE,若有则注释掉这两行; - 执行qmake命令,重新构建项目。
2. 显式调用多字节版本Windows API
无需修改全局字符集,直接指定多字节版本API(函数名后缀加A):
- 第一段代码修改:
m_hDLL = LoadLibraryA(Dll);
- 第二段代码修改:
CDllLoader::HandleFatalError(const char* Dll) { LPVOID lpMsgBuf; // 调用FormatMessageA FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&lpMsgBuf, 0, NULL); // 直接用char*转换,无需LPCTSTR std::string Text((char*)lpMsgBuf); LocalFree(lpMsgBuf); Text += Dll; // 调用FatalAppExitA FatalAppExitA(0, Text.c_str()); }
3. 统一使用Unicode字符集
若项目适合Unicode环境,调整代码适配宽字符:
- 第一段代码修改:
CDllLoader::Load(const wchar_t* Dll, bool* pLoadError /*=NULL*/) { m_hDLL = LoadLibraryW(Dll); }
- 第二段代码修改:
CDllLoader::HandleFatalError(const wchar_t* Dll) { LPVOID lpMsgBuf; FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL); std::wstring Text((LPWSTR)lpMsgBuf); LocalFree(lpMsgBuf); Text += Dll; FatalAppExitW(0, Text.c_str()); }
内容的提问来源于stack exchange,提问作者517453088qqcom
相关产品推荐
相关产品推荐

