2013-12-22 18 views
0

我是Windows API的新手,當我想出如何獲取系統消息代碼描述時,我想知道是否更好,更優雅的方式去做。或者,爲了教育目的,如果通常還有其他方式,則可以使用Windows API - 將FormatMessage()的結果轉換爲std :: string

DWORD WINAPI FormatMessage(
    _In_  DWORD dwFlags, 
    _In_opt_ LPCVOID lpSource, 
    _In_  DWORD dwMessageId, 
    _In_  DWORD dwLanguageId, 
    _Out_  LPTSTR lpBuffer, 
    _In_  DWORD nSize, 
    _In_opt_ va_list *Arguments 
); 

更新的代碼後評論:

std::string bmd2File::getErrorCodeDescription(long errorCode) const throw (bmd2Exception) 
{ 
    #ifdef _WIN32 

    char MessageFromSystem[1024]; 
    bool messageReceived = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 
        0, 
        errorCode, 
        1033,       // US English 
        MessageFromSystem, 
        1024, 
        0); 
    std::ostringstream ostr; 

    if (!messageReceived) 
     ostr << "Error code: " << errorCode; 
    else 
     ostr << "Error code " << errorCode << " with message: " << MessageFromSystem; 

    return ostr.str(); 

    #else 
    #endif 
} 

OLD CODE

std::string bmd2File::getErrorCodeDescription(long errorCode) const throw (bmd2Exception) 
{ 
    #ifdef _WIN32 

    char MessageFromSystem[1024]; 
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 
        0, 
        errorCode, 
        1033,       // US English 
        MessageFromSystem, 
        1024, 
        0); 
    return std::string(MessageFromSystem); 

    #else 
    #endif 
} 

我看起來像一個菜鳥或者是這個代碼好嗎?

+0

謝謝,我會解決的! –

+0

char數組[1024]怎麼樣?似乎低級別以字節爲單位指定一個char數組,並且只是交叉手指以指望它足夠大。 –

+0

而不是硬編碼緩衝區大小讓函數爲您分配它。您可以按位或ORF FORMAT_MESSAGE_ALLOCATE_BUFFER到該函數的第一個參數。 – Vishal

回答

1

這是不行的。從MSDN documentation of FormatMessage,我們看到:

如果函數失敗,則返回值爲零。要獲得擴展錯誤 信息,請調用GetLastError。

這意味着這個函數有可能失敗。您應該檢查返回值以查看它是否失敗並以某種方式處理該錯誤,或​​許通過返回一個錯誤代碼爲GetLastError的字符串。如果您不處理它,那麼您可能會將未初始化的數據傳遞給std::string構造函數,您可能會導致未定義的行爲。

相關問題