【问题标题】:Enabling UNICODE in gcc windows api string processing [duplicate]在 gcc windows api 字符串处理中启用 UNICODE [重复]
【发布时间】:2021-04-08 23:46:18
【问题描述】:

我正在尝试通过 windows wave 设备进行扫描,在test.cpp 中使用以下测试 sn-p;

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; 
} 

使用 gcc version 8.1.0 (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 在 PowerShell 中编译,我收到此错误:

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);

我认为wstring 构造函数包括对 c 样式空终止字符串的支持。为什么会出现此错误?

【问题讨论】:

  • This question 是关于将string 转换为wstring 但答案仍然适用。
  • 如果您的代码页不是 UTF-8 代码页,则必须将字符串正确转换为正确的编码。

标签: c++ mingw-w64 winmm


【解决方案1】:

默认情况下,UNICODE 宏未定义。这使得pzPname 字段在定义中为CHAR pzPname[MAXPNAMELEN]。这就是出现错误的原因,因为 std::wstring 正在尝试使用 char 数据而不是 wchar_t 数据进行初始化。

要解决此问题,请在包含 Windows.h 文件之前放置 #define UNICODE 语句,或改用 std::string

【讨论】:

  • 谢谢,有道理。定义UNICODE 解决了这个问题。
  • 或者,您可以直接忘记UNICODE,直接使用waveOutDevCapsW()/WAVEOUTCAPSW
猜你喜欢
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2014-06-14
  • 2014-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多