关于MultiByteToWideChar的疑惑?
本帖最后由 zgxyz2010 于 2012-12-24 19:12:28 编辑 windows核心编程上说MultiByteToWideChar函数最后一个参数cchWideChar表示的是字节数,即nlen*sizeof(wchar_t),但是后面的例子却是用的字符数nlen,msdn上没看懂好像也是说的字节数额,百度百科上说是字符数。写了代码来测试,发现两种都得到正确结果。求指教~
[解决办法]
[in] Size, in WCHAR values, of the buffer indicated by lpWideCharStr
换句话说 就是有多少个 wchar
你填入了 2倍的 缓冲大小 nlen*sizeof(wchar_t)自然也不会错
用到多少个 WCHAR 取决于你要转换多少个 MultiByte
wstring s2ws(const string& s)
{
int len = MultiByteToWideChar(CP_OEMCP, 0, s.c_str(), s.size(), NULL, 0);
wstring ws;
ws.resize(len);
MultiByteToWideChar(CP_OEMCP, 0, s.c_str(), s.size(), &ws[0], len);
return ws;
}
比如
wstring ws = s2ws("wjs我");
len = 4;
你提供的 cchWideChar 至少为4个 当然 你多提供了 提供8个也没问题
[解决办法]
cchWideChar 是字符数
Size, in characters, of the buffer indicated by lpWideCharStr. If this value is 0, the function returns the required buffer size, in characters, including any terminating null character, and makes no use of the lpWideCharStr buffer.
来自 http://msdn.microsoft.com/en-us/library/dd319072(v=VS.85).aspx
in characters 是 字符的意思
[解决办法]
in characters在WideChar语境下和in bytes不是一回事。