【发布时间】: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 的行为与gcc 和clang 不同,即
// 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)
gcc 和 clang 的 boost 实现似乎只使用了我的输入 wchar_t 的最后 2 个字节,尽管它在输入的开始和结束地址方面被正确解析。
我错过了什么?
【问题讨论】:
-
from_utf(utf16String, "UTF-16")? -
@YSC 不。目标应该是“UTF-8”
-
new...memset...memcpy...reinterpret_cast<void*>引发如此许多危险信号。重新考虑这段代码。 -
@KonradRudolph 真实故事.. 认为它是 alpha 版本 ;-)
-
实际上我认为它对我有用,使用 GCC/Boost Coliru 使用的任何东西:coliru.stacked-crooked.com/a/f8c3a165a41dc5ec(注意内存布局不同,因为
wchar_t在这个平台上显然是 4 个字节)。
标签: c++ visual-studio gcc boost clang