gpt4 book ai didi

c++ - 如何从 GetLastError() 返回的错误码中获取错误信息?

转载 作者:IT老高 更新时间:2023-10-28 11:52:07 31 4
gpt4 key购买 nike

在 Windows API 调用之后,如何以文本形式获取最后一条错误消息?

GetLastError() 返回一个整数值,而不是文本消息。

最佳答案

//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
//Get the error message ID, if any.
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0) {
return std::string(); //No error message has been recorded
}

LPSTR messageBuffer = nullptr;

//Ask Win32 to give us the string version of that message ID.
//The parameters we pass in, tell Win32 to create the buffer that holds the message for us (because we don't yet know how long the message string will be).
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

//Copy the error message into a std::string.
std::string message(messageBuffer, size);

//Free the Win32's string's buffer.
LocalFree(messageBuffer);

return message;
}

关于c++ - 如何从 GetLastError() 返回的错误码中获取错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1387064/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com