我应该如何在 C 中正确使用 FormatMessage() ?

新手上路,请多包涵

没有

  • MFC
  • ATL

如何使用 FormatMessage() 获取 HRESULT 的错误文本?

  HRESULT hresult = application.CreateInstance("Excel.Application");

 if (FAILED(hresult))
 {
     // what should i put here to obtain a human-readable
     // description of the error?
     exit (hresult);
 }

原文由 Aaron 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 591
2 个回答

这是从系统返回错误消息的正确方法 HRESULT (在这种情况下命名为 hresult,或者您可以将其替换为 GetLastError() ):

 LPTSTR errorText = NULL;

FormatMessage(
   // use system message tables to retrieve error text
   FORMAT_MESSAGE_FROM_SYSTEM
   // allocate buffer on local heap for error text
   |FORMAT_MESSAGE_ALLOCATE_BUFFER
   // Important! will fail otherwise, since we're not
   // (and CANNOT) pass insertion parameters
   |FORMAT_MESSAGE_IGNORE_INSERTS,
   NULL,    // unused with FORMAT_MESSAGE_FROM_SYSTEM
   hresult,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   (LPTSTR)&errorText,  // output
   0, // minimum size for output buffer
   NULL);   // arguments - see note

if ( NULL != errorText )
{
   // ... do something with the string `errorText` - log it, display it to the user, etc.

   // release memory allocated by FormatMessage()
   LocalFree(errorText);
   errorText = NULL;
}

这与大卫哈纳克的答案之间的主要区别是使用 FORMAT_MESSAGE_IGNORE_INSERTS 标志。 MSDN 对如何使用插入有点不清楚,但 Raymond Chen 指出,在检索系统消息时永远不要使用它们,因为您无法知道系统期望哪些插入。

FWIW,如果您使用的是 Visual C++,您可以使用 _com_error 类让您的生活更轻松:

 {
   _com_error error(hresult);
   LPCTSTR errorText = error.ErrorMessage();

   // do something with the error...

   //automatic cleanup when error goes out of scope
}

据我所知,它不是 MFC 或 ATL 的一部分。

原文由 Shog9 发布,翻译遵循 CC BY-SA 4.0 许可协议

从 c++11 开始,您可以使用标准库代替 FormatMessage

 #include <system_error>

std::string message = std::system_category().message(hr)

原文由 Chronial 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题