前言
大家在學習或者使用Windows編程中,經常會碰到字符串之間的轉換,char*轉LPCWSTR也是其中一個比較常見的轉換。下面就列出幾種比較常用的轉換方法。大家可以根據自己的需求選擇相對應的方法,下面來一起學習學習吧。
1、通過MultiByteToWideChar函數轉換
MultiByteToWideChar函數是將多字節轉換為寬字節的一個API函數,它的原型如下:
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 *類型
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轉換宏
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轉換
char* szStr = "測試字符串"; CString str = CString(szStr); USES_CONVERSION; LPCWSTR wszClassName = A2CW(W2A(str)); str.ReleaseBuffer();
上述方法都是UniCode環境下測試的。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答