windows函数 MultiByteToWideChar提供将多字节字符串转换为宽字节字符串的功能(参考windows核心编程2.8)。
int MultiByteToWideChar(
UINT uCodePage,
DWORD dwFlags,
PCSTR pMultiByteStr,
int cbMultiByte,
PWSTR pWideCharStr,
int cchWideChar);
uCodePage标识与多字节字符关联的代码页值(个人理解指当前多字节的编码格式)。
dwFlags提供一些额外的标识,这里写0.
pMultiByteStr指定要转换的字符串。
cbMultiByte指定字符串的长度(传入-1,函数可自动判断源字符串长度)。
pWideCharStr转换所得宽字节字符串的内存地址。
cchWideChar宽字节字符串的长度(传入0函数不会执行,而是返回一个宽字节数包括终止符‘\0’)。
操作步骤:
1.调用MultiByteToWideChar,为pWideCharStr 传入NULL,cchWideChar传入0,cbMultiByte传入-1,得到要转换宽字节字符数count。
2.申请长度为count*sizeof(wchar_t)的内存空间,用于存放转换的宽字节字符串。
3.再次调用MultiByteToWideChar,传入指定的参数,便可获取转换完的宽字节字符串。
4.释放申请的内存块。
参考代码:
string strRet = GetStr(pszTable, pszField, id);
int len = MultiByteToWideChar(CP_UTF8, 0, strRet.c_str(), -1, NULL, 0);
wchar_t* wstr = new wchar_t[len];
len *= sizeof(wchar_t);
memset(wstr, 0, len);
MultiByteToWideChar(CP_UTF8, 0, strRet.c_str(), -1, wstr, len);
delete wstr;
wstr = nullptr;