How should I use FormatMessage() properly in C++?

后端 未结 8 850
悲&欢浪女
悲&欢浪女 2020-11-28 03:28

Without:

  • MFC
  • ATL

How can I use FormatMessage() to get the error text for a HRESULT?

 HRES         


        
8条回答
  •  悲&欢浪女
    2020-11-28 04:08

    As pointed out in other answers:

    • FormatMessage takes a DWORD result not a HRESULT (typically GetLastError()).
    • LocalFree is needed to release memory that was allocated by FormatMessage

    I took the above points and added a few more for my answer:

    • Wrap the FormatMessage in a class to allocate and release memory as needed
    • Use operator overload (e.g. operator LPTSTR() const { return ...; } so that your class can be used as a string
    class CFormatMessage
    {
    public:
        CFormatMessage(DWORD dwMessageId,
                       DWORD dwLanguageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)) :
            m_text(NULL)
        {
            Assign(dwMessageId, dwLanguageId);
        }
    
        ~CFormatMessage()
        {
            Clear();
        }
    
        void Clear()
        {
            if (m_text)
            {
                LocalFree(m_text);
                m_text = NULL;
            }
        }
    
        void Assign(DWORD dwMessageId,
                    DWORD dwLanguageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT))
        {
            Clear();
            DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM
                | FORMAT_MESSAGE_ALLOCATE_BUFFER
                | FORMAT_MESSAGE_IGNORE_INSERTS,
            FormatMessage(
                dwFlags,
                NULL,
                dwMessageId,
                dwLanguageId,
                (LPTSTR) &m_text,
                0,
                NULL);
        }
    
        LPTSTR text() const { return m_text; }
        operator LPTSTR() const { return text(); }
    
    protected:
        LPTSTR m_text;
    
    };
    

    Find a more complete version of the above code here: https://github.com/stephenquan/FormatMessage

    With the above class, the usage is simply:

        std::wcout << (LPTSTR) CFormatMessage(GetLastError()) << L"\n";
    

提交回复
热议问题