std::string Window::Exception::TranslateErrorCode(HRESULT hr) noexcept
{
char* pMsgBuf = nullptr;
DWORD nMsgLen = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPWSTR>(&pMsgBuf),
0,
nullptr
);
if (nMsgLen == 0)
{
return "Unidentified error code";
}
std::string errorString = pMsgBuf;
LocalFree(pMsgBuf);
return errorString;
}
这是返回描述字符串的代码,但是描述上的字符串只有1个字母长,我认为问题在于pMsgBuf是LPWSTR,但我不知道如何使用LPSTR设置reinterpret_cast,因为如果我输入 LPSTR 它会给我一个错误: “‘LPSTR’类型的参数与‘LPWSTR’类型的参数不兼容”
首先,现在是 2024 年,在现代应用程序中使用 ANSI 字符串是不可原谅的。
std::wstring Window::Exception::TranslateErrorCode(HRESULT hr) noexcept
{
LPWSTR pBuffer = nullptr;
DWORD Result = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPWSTR>(&pBuffer),
0,
nullptr);
if (Result == 0) {
return L"Unidentified error code";
}
std::wstring ErrorString = pBuffer;
LocalFree(pBuffer);
return ErrorString;
}
其次,您将
HRESULT
传递到此代码中。虽然您可以从中获取错误消息文本,但您需要注意并非所有 HRESULT 代码都来自 FACILITY_WIN32
并且您返回的错误消息可能完全错误。