【问题标题】:Convert wchar_t to char with boost locale使用 boost 语言环境将 wchar_t 转换为 char
【发布时间】:2016-07-05 01:30:56
【问题描述】:

我的目标是将wchar_t 转换为char,我的方法是使用boost::locale(使用boost 1.60)。例如,

wchar_t * myWcharString = "0000000002" (Memory 0x 30 00 30 00 ... 32 00)

char * myCharString = "0000000002" (Memory 0x 30 30 ... 32)

我写了一个函数:

inline char* newCharFromWchar(wchar_t * utf16String) {
    char * cResult = NULL;
    try {
        std::string szResult = boost::locale::conv::from_utf(utf16String, "UTF-8");
        cResult = new char[szResult.size() + 1];
        memset(reinterpret_cast<void*>(cResult), 0, szResult.size() + 1);
        memcpy(reinterpret_cast<void*>(cResult),
           reinterpret_cast<const void*>(szResult.c_str()),
           szResult.size());
    }
    catch (...) {
        // boost::locale::conv might throw
    }
    return cResult;
}

现在的问题是VS2013 的行为与gccclang 不同,即

// VS 2013 behaves as expected
wchar_t * utf16String = "0000000002" (Memory 0x 30 00 30 00 ... 32 00)
char * cResult = "0000000002" (Memory 0x 30 30 ... 32)

// both gcc and clang NOT as expected:
wchar_t * utf16String = "0000000002" (Memory 0x 30 00 30 00 ... 32 00)
char * cResult = "2" (Memory 0x 32)

gccclang 的 boost 实现似乎只使用了我的输入 wchar_t 的最后 2 个字节,尽管它在输入的开始和结束地址方面被正确解析。

我错过了什么?

【问题讨论】:

  • from_utf(utf16String, "UTF-16")?
  • @YSC 不。目标应该是“UTF-8”
  • new ... memset ... memcpy ... reinterpret_cast&lt;void*&gt; 引发如此许多危险信号。重新考虑这段代码。
  • @KonradRudolph 真实故事.. 认为它是 alpha 版本 ;-)
  • 实际上我认为它对我有用,使用 GCC/Boost Coliru 使用的任何东西:coliru.stacked-crooked.com/a/f8c3a165a41dc5ec(注意内存布局不同,因为wchar_t 在这个平台上显然是 4 个字节)。

标签: c++ visual-studio gcc boost clang


【解决方案1】:

VS2013 将wchar_t 作为 16 位字符,而 gcc 和 clang 都将它作为 32 位字符(在我的机器上)。

因此,如果我将 0x 30 00 30 00 ... 32 00 存储为 wchar_t,它只能按预期与 VS2013 一起使用。 boost::locale 将假定 0x 30 00 30 00 是一个字符,而不是我预期的两个字符。因此,这些平台之间的结果输出完全不同。

【讨论】:

    猜你喜欢
    • 2013-01-20
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多