yohhoyの日記

技術的メモをしていきたい日記

HRESULT型からのエラーメッセージ取得

WindowsOS環境のHRESULT型エラーコードからエラーメッセージ文字列へのお手軽変換。Microsoft Visual C++(MSVC)限定。

#include <windows.h>
#include <system_error>

std::string get_message(HRESULT hr)
{
  return std::system_category().message(hr);
}

// GetLastError()戻り値などDWORD型 Windows Error Code の場合は、
// HRESULT_FROM_WIN32マクロによりHRESULT型へと事前変換する。

上記コードではWindows OSのロケールに応じた文字列(日本語OSなら日本語のメッセージ)が取得される。英語メッセージで固定したい場合などは、FormatMessage関数を自前で呼び出す必要がある。

おまけ:FormatMessage関数のdwLanguageId引数=0で実装されているため*1SetThreadUILanguage関数でスレッドのLANGIDを事前に変更しておく案もある。シングルスレッドプログラムならこれでもいいか...

関連URL

*1:"If you pass in zero, FormatMessage looks for a message for LANGIDs in the following order: 1.Language neutral / 2.Thread LANGID, based on the thread's locale value / 3.(snip)"