C/C++,Windows/MFC__char与TCHAR相互转化

来源:互联网 发布:徐州八方网络 编辑:程序博客网 时间:2024/05/18 15:50
char与TCHAR之间的转化主要用到函数MultiByteToWideChar和WideCharToMultiByte
char转TCHAR

如果不是Unicode字符集,就不需要转换,直接复制即可,如果不确定是否使用Unicode字符集,可以这样写

[cpp] view plaincopy
  1. char strUsr[10] = "Hello";  
  2. TCHAR Name[100];  
  3. #ifdef UNICODE  
  4.     MultiByteToWideChar(CP_ACP, 0, strUsr, -1, Name, 100);  
  5. #else  
  6.     strcpy(Name, strUsr);  
  7. #endif  
TCHAR转char

[cpp] view plaincopy
  1. char* ConvertLPWSTRToLPSTR (LPWSTR lpwszStrIn)  
  2. {  
  3.     LPSTR pszOut = NULL;  
  4.     if (lpwszStrIn != NULL)  
  5.     {  
  6.         int nInputStrLen = wcslen (lpwszStrIn);  
  7.   
  8.         // Double NULL Termination  
  9.         int nOutputStrLen = WideCharToMultiByte (CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;  
  10.         pszOut = new char [nOutputStrLen];  
  11.   
  12.         if (pszOut)  
  13.         {  
  14.             memset (pszOut, 0x00, nOutputStrLen);  
  15.             WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);  
  16.         }  
  17.     }  
  18.     return pszOut;  
  19. }  
0 0