c++openglglsllpwstr

Print opengl shader compile log with wprintf


Following the tutorials at opengl-tutorial.org , realize that I can't print the shader compile log directly with printf because I'm doing it in a windows desktop application. I tried to convert it to a LPWSTR using this method:

//compile the shader
glShaderSource(fShader, 1, &pFsCode, NULL);
glCompileShader(fShader);

//check shader compilation
glGetShaderiv(fShader, GL_COMPILE_STATUS, &result);
glGetShaderiv(fShader, GL_INFO_LOG_LENGTH, &logLen);
if (logLen > 0) {
    //get compile log
    vector<char> fErr(logLen + 1);
    glGetShaderInfoLog(fShader, logLen, NULL, &fErr[0]);

    //try to convert log to LPWSTR
    wchar_t msg[100];
    swprintf(msg, sizeof(msg) / sizeof(*msg), L"%s\n", &fErr[0]);

    //print it
    wprintf(msg);
}

For some reason, I get this output:

⤱㨠攠牲牯䌠㄰ㄲ›瘣牥楳湯㌠〰洠獵⁴敢映汯潬敷⁤祢攠ੳ⠰⤲㨠攠牲牯䌠㈰㄰›湵畳灰牯整⁤敶獲潩〳ਰ⠰⤲㨠攠牲牯䌠〰〰›祳瑮硡攠牲牯‬湵硥数瑣摥✠✨‬硥数瑣湩⁧㨢∺愠⁴潴敫⠢ਢ⠰⤴㨠攠牲牯䌠㔷㈳

Can someone please tell me why I get this corrupt output?

All help is appreciated.


Solution

  • You're not converting the chars to wchar_ts using swprintf(..., "%s\n", ...) because, according to https://msdn.microsoft.com/en-us/library/hf4y5e3w.aspx %s means the following:

    When used with printf functions, specifies a single-byte or multi-byte character string; when used with wprintf functions, specifies a wide-character string. Characters are displayed up to the first null character or until the precision value is reached.

    As you're indeed using a *wprintf function here, %s already expects a wide string, but you give it a non-wide string. So the ascii text (in this case 1) : error C0121: #version 300 must be followed by ...) is interpreted as wide string instead, resulting in garbage.

    According to the same webpage, %S might be the quickest fix to resolve your problem here ("when used with wprintf functions, specifies a single-byte or multi-byte character string" - what %s is for normal printf).