Search code examples
c++error-handlingexitwidechar

Wide Char Version of Get last Error?


This is Microsoft's code:

void ErrorExit(LPCWSTR lpszFunction, DWORD NTStatusMessage)
{
    // Retrieve the system error message for the last-error code
    DWORD dww = 0;
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;

    if (NTStatusMessage)
    {
        dww = NTStatusMessage;
        FormatMessageW( 
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM | 
        FORMAT_MESSAGE_FROM_HMODULE,
        hdlNtCreateFile,
        dww,  
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPWSTR) &lpMsgBuf,  
        0,  
        NULL );
    }
    else
    {

        dww = GetLastError();

    FormatMessageW(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dww,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),  (LPWSTR)&lpMsgBuf,0, NULL);
    }
    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));


    StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error %lu: %s"), lpszFunction, dww, lpMsgBuf);
    printf("\a");  //audible bell not working yet
    MessageBoxW(NULL, (LPCTSTR)lpDisplayBuf, L"Error", MB_OK);
    LocalFree(lpDisplayBuf);

    LocalFree(lpMsgBuf);

    //ExitProcess(dw);
}

I added a section for NTstatus and changed the arg to LPCWSTR. It's basically nonfunctional as simply changing to StringCchPrintfW segfaults on the LPVOID types. Any way of making it wide char friendly?


Solution

  • This problem was solved by adding _UNICODE and UNICODE to the Preprocessor definitions in C/C++ > Preprocessor.
    The MessageBox call in the OP code adjusted a little: thanks to someone knowledgeable on the Microsoft forums.