MultiByteToWideChar将多字节字符串转换为宽字符字符串,函数原型如下:
int MultiByteToWideChar( __in UINT CodePage, //与多字节字符串关联的一个代码页值,一般设为CP_ACP __in DWORD dwFlags, //指定额外的转换控制,一般为0 __in LPCSTR lpMultiByteStr, //要转换的多字节字符串 __in int cbMultiByte, //多字节字符串字节数,为-1则自动判断字符串长度 __out LPWSTR lpWideCharStr, //转换后Unicode字符串的缓冲区 __in int cchWideChar //接收缓冲区最大长度(字符数) );
一般按下面步骤将一个多字节字符串转换为Unicode形式:
1)调用MultiByteToWideChar,为lpWideCharStr传入NULL,为cchWideChar传入0,为cbMultiByte传入-1;
2)分配一块足以容纳转换后的Unicode字符串的内存,它的大小是1)中函数返回值乘以sizeof(wchar_t);
3)再次调用MultiByteToWideChar,这次将缓冲区地址作为lpWideCharStr参数的值传入,将1)中函数返回值乘以sizeof(w_char_t)后得到的大小作为cchWideChar参数的值传入;
4)使用转换后的字符串;
5)释放Unicode字符串占用的内存块。
下面是我们封装的多字节字符串转Unicode字符串的函数和字符字符串转换为多字节字符串函数:
int ToWideString( WCHAR* &pwStr, const char* pStr, int len, BOOL IsEnd) { ASSERT_POINTER(pStr, char); ASSERT(len >= 0 || len == -1); int nWideLen = MultiByteToWideChar(CP_ACP, 0, pStr, len, NULL, 0); if (len == -1) { --nWideLen; } if (nWideLen == 0) { return 0; } if (IsEnd) { pwStr = new WCHAR[(nWideLen+1)*sizeof(WCHAR)]; ZeroMemory(pwStr, (nWideLen+1)*sizeof(WCHAR)); } else { pwStr = new WCHAR[nWideLen*sizeof(WCHAR)]; ZeroMemory(pwStr, nWideLen*sizeof(WCHAR)); } MultiByteToWideChar(CP_ACP, 0, pStr, len, pwStr, nWideLen); return nWideLen; }
int ToMultiBytes( char* &pStr, const WCHAR* pwStr, int len, BOOL IsEnd) { ASSERT_POINTER(pwStr, WCHAR) ; ASSERT( len >= 0 || len == -1 ) ; int nChars = WideCharToMultiByte(CP_ACP, 0, pwStr, len, NULL, 0, NULL, NULL); if (len == -1) { --nChars; } if (nChars == 0) { return 0; } if(IsEnd) { pStr = new char[nChars+1]; ZeroMemory(pStr, nChars+1); } else { pStr = new char[nChars]; ZeroMemory(pStr, nChars); } WideCharToMultiByte(CP_ACP, 0, pwStr, len, pStr, nChars, NULL, NULL); return nChars; }
//调用方式如下: char *pStr = "ASCE1885"; WCHAR *pwStr; int nWideLen = ToWideString(pwStr, pStr, -1, TRUE); WCHAR *pwStr = _T("ASCE1885"); char *pStr; int nWideLen = ToMultiBytes(pStr, pwStr, -1, TRUE);