c++mingw-w64winmm

Enabling UNICODE in gcc windows api string processing


I am trying scan thru windows wave devices, using following test snippet in test.cpp;

using namespace std;
#include <string>
#include <vector>
#include <Windows.h>

int main () 
{ 
    int nDeviceCount = waveOutGetNumDevs();
    vector<wstring> sDevices;
    WAVEOUTCAPS woc;
    for (int n = 0; n < nDeviceCount; n++)
        if (waveOutGetDevCaps(n, &woc, sizeof(WAVEOUTCAPS)) == S_OK) {
            wstring dvc(woc.szPname);
            sDevices.push_back(dvc);
        }
    return 0; 
} 

Compiled in PowerShell with gcc version 8.1.0 (i686-posix-dwarf-rev0, Built by MinGW-W64 project), I get this error:

PS xxx> g++ .\test.cpp -c
.\test.cpp: In function 'int main()':
.\test.cpp:14:27: error: no matching function for call to 'std::__cxx11::basic_string<wchar_t>::basic_string(CHAR [32])'
    wstring dvc(woc.szPname);

I thought wstring constructor includes support for c-style null-terminated strings. Why am I getting this error?


Solution

  • By default, the UNICODE macro is undefined. This makes the pzPname field be CHAR pzPname[MAXPNAMELEN] in the definition. That’s why the error arises, as the std::wstring is trying to initialize with char data rather than wchar_t data.

    To resolve this, place a #define UNICODE statement before including the Windows.h file, or use std::string instead.