GetLastError() can be somehow passed to FormatMessageW to get a formatted message. The objective is to get a QString at the end. What is the correct and safe way of doing it?

有帮助吗?

解决方案

This does the trick.

QString getLastErrorMsg() {
    LPWSTR bufPtr = NULL;
    DWORD err = GetLastError();
    FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | 
                   FORMAT_MESSAGE_FROM_SYSTEM |
                   FORMAT_MESSAGE_IGNORE_INSERTS,
                   NULL, err, 0, (LPWSTR)&bufPtr, 0, NULL);
    const QString result = 
        (bufPtr) ? QString::fromUtf16((const ushort*)bufPtr).trimmed() :
                   QString("Unknown Error %1").arg(err);
    LocalFree(bufPtr);
    return result;
}

One should always specify FORMAT_MESSAGE_IGNORE_INSERTS when calling FormatMessage. Some error messages do contain placeholders, which will lead to bugs, unless your code passes an argument list. Since we're passing NULL this would be bug waiting to happen.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top