C++ 有没有办法使用 win API 获取 HRESULT 值的字符串表示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7008047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get the string representation of HRESULT value using win API?
提问by khkarens
Is there a function in win API which can be used to extract the string representation of HRESULT value?
win API 中是否有可用于提取 HRESULT 值的字符串表示的函数?
The problem is that not all return values are documented in MSDN, for example ExecuteInDefaultAppDomain()function is not documented to return "0x80070002 - The system cannot find the file specified.", however, it does! Therefore, I was wondering whether there is a function to be used in common case.
问题是并非所有返回值都记录在 MSDN 中,例如ExecuteInDefaultAppDomain()函数未记录为返回“0x80070002 - 系统找不到指定的文件。”,但是,它确实如此!因此,我想知道是否有一个函数可以在普通情况下使用。
回答by eran
You can use _com_error:
您可以使用_com_error:
_com_error err(hr);
LPCTSTR errMsg = err.ErrorMessage();
If you don't want to use _com_error
for whatever reason, you can still take a look at its source, and see how it's done.
如果您_com_error
出于任何原因不想使用,您仍然可以查看它的来源,看看它是如何完成的。
Don't forget to include the header comdef.h
不要忘记包含标题 comdef.h
回答by Chronial
Since c++11, this functionality is built into the standard library:
从 c++11 开始,此功能内置于标准库中:
#include <system_error>
std::string message = std::system_category().message(hr)
回答by Simon Mourier
The Windows API for this is FormatMessage. Here is a link that explains how to do it: Retrieving Error Messages.
Windows API 是FormatMessage。这是一个解释如何执行此操作的链接:检索错误消息。
For Win32 messages (messages with an HRESULT that begins with 0x8007, which is FACILITY_WIN32), you need to remove the hi order word. For example in the 0x80070002, you need to call FormatMessage with 0x0002.
对于 Win32 消息(具有以 0x8007 开头的 HRESULT 的消息,即 FACILITY_WIN32),您需要删除 hi 命令字。例如在 0x80070002 中,您需要使用 0x0002 调用 FormatMessage。
However, it does not always work for any type of message. And for some specific messages (specific to a technology, a vendor, etc.), you need to load the corresponding resource DLL, which is not always an easy task, because you need to find this DLL.
但是,它并不总是适用于任何类型的消息。而对于某些特定的消息(特定于某项技术、某个供应商等),您需要加载相应的资源 DLL,这并不总是一件容易的事,因为您需要找到这个 DLL。
回答by WebDrive
Here's a sample using FormatMessage()
这是使用 FormatMessage() 的示例
LPTSTR SRUTIL_WinErrorMsg(int nErrorCode, LPTSTR pStr, WORD wLength )
{
try
{
LPTSTR szBuffer = pStr;
int nBufferSize = wLength;
//
// prime buffer with error code
//
wsprintf( szBuffer, _T("Error code %u"), nErrorCode);
//
// if we have a message, replace default with msg.
//
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
NULL, nErrorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) szBuffer,
nBufferSize,
NULL );
}
catch(...)
{
}
return pStr;
} // End of SRUTIL_WinErrorMsg()