Unicode與Ansi互轉
阿新 • • 發佈:2017-07-15
form nic code 手動 char empty ret wchar art
1 BOOL CTool::AnsiToUnicode(const char *pSrc, CString &strResult) 2 { 3 #ifndef _UNICODE 4 return FALSE; 5 #endif 6 int nLen=MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,pSrc,-1,NULL,0); 7 strResult.Empty(); 8 if(nLen==0) 9 return FALSE; 10 wchar_t* pResult=new wchar_t[nLen];11 MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,pSrc,-1,pResult,nLen); 12 strResult.Format(_T("%s"),pResult); 13 delete[] pResult; 14 pResult=NULL; 15 return TRUE; 16 } 17 18 wchar_t* CTool::AnsiToUnicode(const char *szStr) 19 { 20 int nLen=MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,szStr,-1,NULL,0); 21 if(nLen==0) 22 return NULL; 23 wchar_t* pResult=new wchar_t[nLen]; 24 MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,szStr,-1,pResult,nLen); 25 return pResult; 26 } 27 28 char* CTool::UnicodeToAnsi(const wchar_t *szStr) 29 { 30 int nLen=WideCharToMultiByte(CP_ACP,0,szStr,-1,NULL,0,NULL,NULL); 31 if(nLen==0) 32 return NULL; 33 char* pResult=new char[nLen]; 34 WideCharToMultiByte(CP_ACP,0,szStr,-1,pResult,nLen,NULL,NULL); 35 return pResult; 36 }
後面兩個函數返回一個new的指針,接收用完後需要自己手動釋放
Unicode與Ansi互轉