我有一个Win32函数需要移植到iOS:
我正在使用C++,而不是Objective C,并且一直在尝试使用mbstowcs和_mbstowcs_l。它们似乎与MultiByteToWideChar的行为不同。例如,单词attaché末尾的重音字符未被正确转换(Win32版本正确转换)。是否在标准库中有“UTF-8到UTF-16”的功能?
Win32版本中是否存在我没有注意到的错误?
从MultiByteToWideChar返回的长度小于从mbstowcs返回的长度。
奇怪的是,在这个小测试案例中
// Loads UTF-8 file and converts to a UTF-16 string
bool LoadUTF8File(char const *filename, wstring &str)
{
size_t size;
bool rc = false;
void *bytes = LoadFile(filename, &size);
if(bytes != 0)
{
int len = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)bytes, size, 0, 0);
if(len > 0)
{
str.resize(len + 1);
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)bytes, size, &str[0], len);
str[len] = '\0';
rc = true;
}
delete[] bytes;
}
return rc;
}
// LoadFile returns the loaded file as a block of memory
// There is a 3 byte BOM which MultiByteToWideChar seems to ignore
// The text in the file is encoded as UTF-8
我正在使用C++,而不是Objective C,并且一直在尝试使用mbstowcs和_mbstowcs_l。它们似乎与MultiByteToWideChar的行为不同。例如,单词attaché末尾的重音字符未被正确转换(Win32版本正确转换)。是否在标准库中有“UTF-8到UTF-16”的功能?
Win32版本中是否存在我没有注意到的错误?
从MultiByteToWideChar返回的长度小于从mbstowcs返回的长度。
奇怪的是,在这个小测试案例中
char *p = "attaché";
wstring str;
size_t size = strlen(p);
setlocale(LC_ALL, "");
int len = mbstowcs(null, p, size);
if(len > 0)
{
str.resize(len + 1);
mbstowcs(&str[0], p, size);
str[len] = '\0';
}
TRACE(L"%s\n", str.c_str());
len = MultiByteToWideChar(CP_UTF8, 0, p, size, null, 0);
if(len > 0)
{
str.resize(len + 1);
MultiByteToWideChar(CP_UTF8, 0, p, size, &str[0], len);
str[len] = '\0';
}
TRACE(L"%s\n", str.c_str());
我使用mbcstowcs得到了正确的输出,但MultiByteToWideChar将最后一个字符错误地转换为65533(REPLACEMENT_CHARACTER)。现在我很困惑...
mbstowcs
之前,你是否调用了setlocale("");
? - Kerrek SB