我的函数GetErrorString()传递了一个错误代码,它是WSAGetLastError()的结果,或者是我的DLL中定义的错误代码之一,当我的DLL函数调用无法完成时会返回。
我有一个std :: pairs数组,它存储我的错误代码及其const char *错误字符串
std::pair<int, const char*> errorCodeArray[12] =
{
std::pair<int,char*>(0,"Success"),
std::pair<int,char*>(1,"Connection Error"),
std::pair<int,char*>(2,"Request Timed Out"),
// ..etc
};
如果错误代码来自WSAGetLastError(),那么我必须使用FormatMessage将错误字符串作为LPWSTR获取,然后将其转换为char *,我找到了这个页面:
How do I convert from LPCTSTR to std::string?
并尝试了这种灵魂,这显然与LPCTSTR一起使用
int size = WideCharToMultiByte(CP_ACP, 0, errCode, -1, 0, 0, NULL, NULL);
char* buf = new char[size];
WideCharToMultiByte(CP_ACP, 0, errCode, -1, buf, size, NULL, NULL);
std::string str(buf);
delete[] buf;
return str.c_str();
但它似乎不适用于LPWSTR,结果总是“????????????”我并不太了解字符编码,无法找到解决方案。
有人可以对此有所了解吗?感谢。
答案 0 :(得分:2)
FormatMessage()作为两个函数提供:
FormatMessageA()
FormateMessageW()
明确使用FormatMessageA()
以避免转换的必要性。
虽然这不能直接回答这个问题,但它提供了一个解决方案,删除了从LPWSTR
转换为char*
的要求。
答案 1 :(得分:1)
你可能想查看wcstombs函数来转换它