My function GetErrorString() is passed an error code which is either the result of WSAGetLastError(), or one of the error codes defined in my DLL, which are returned when calls to my DLL functions are unable to complete.
I have an array of std::pairs which store my error codes along with their const char* error strings
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
};
If the errorcode is from WSAGetLastError() then I must use FormatMessage to get the error string as a LPWSTR, then convert it to a char*, I found this page:
How do I convert from LPCTSTR to std::string?
and tried this soultion which apparently works with 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();
but it doesn’t seem to work with LPWSTR, the result is always “???????????” and I don’t really understand character encoding enough to figure out a solution.
Can anyone shed some light on this? Thanks.
FormatMessage() is provided as two functions:
FormatMessageA()FormateMessageW()Use
FormatMessageA()explicitly to avoid necessity for conversion.While this does not directly answer the question, it provides a solution by removing the requirement to convert from
LPWSTRto achar*.