在Windows程式設計中,經常會碰到字串之間的轉換,char*轉LPCWSTR也是其中一個比較常見的轉換。下面就列出幾種比較常用的轉換方法。
1、通過 MultiByteToWideChar 函式轉換
MultiByteToWideChar函式是將多位元組轉換為寬位元組的一個API函式,它的原型如下:
1 2 3 4 5 6 7 8 |
int MultiByteToWideChar( UINT CodePage, // code page DWORD dwFlags, // character-type options LPCSTR lpMultiByteStr, // string to map int cbMultiByte, // number of bytes in string LPWSTR lpWideCharStr, // wide-character buffer int cchWideChar // size of buffer ); |
LPCWSTR實際上也是CONST WCHAR *型別
1 2 3 4 5 |
char* szStr = "測試字串"; WCHAR wszClassName[256]; memset(wszClassName,0,sizeof(wszClassName)); MultiByteToWideChar(CP_ACP,0,szStr,strlen(szStr)+1,wszClassName, sizeof(wszClassName)/sizeof(wszClassName[0])); |
2、通過 T2W 轉換巨集
1 2 3 4 5 6 |
char* szStr = "測試字串"; CString str = CString(szStr); USES_CONVERSION; LPCWSTR wszClassName = new WCHAR[str.GetLength()+1]; wcscpy((LPTSTR)wszClassName,T2W((LPTSTR)str.GetBuffer(NULL))); str.ReleaseBuffer(); |
3、通過 A2CW 轉換
1 2 3 4 5 |
char* szStr = "測試字串"; CString str = CString(szStr); USES_CONVERSION; LPCWSTR wszClassName = A2CW(W2A(str)); str.ReleaseBuffer(); |
上述方法都是UniCode環境下測試的。