将LPWSTR转换为char * / string

问题描述 投票:0回答:2

我的函数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,结果总是“????????????”而且我并不真正理解字符编码足以找出解决方案。

任何人都可以对此有所了解吗?谢谢。

c++ string character-encoding
2个回答
2
投票

FormatMessage()提供两个功能:

  • FormatMessageA()
  • FormateMessageW()

明确使用FormatMessageA()以避免转换的必要性。

虽然这并没有直接回答这个问题,但它提供了一个解决方案,即删除了从LPWSTR转换为char*的要求。


1
投票

您可能希望查看wcstombs函数以进行转换

© www.soinside.com 2019 - 2024. All rights reserved.