Windows 下 Char 和Wchar的转换

刚封装了一个C的方法,碰到最多的就是char 和Wchar的转化问题. 找了些资料:

1.头文件中要定义宏;       

   #define   UNICODE #define _UNICODE
2.char转换成wchar      

  const   char   *pFilePathName   =    "c:\\aa.dll ";     

  int   nLen   =   strlen(pFilePathName)   +   1;      

  int   nwLen   =   MultiByteToWideChar(CP_ACP,   0,   pFilePathName,   nLen,   NULL,   0); 
 TCHAR   lpszFile[256];     

   MultiByteToWideChar(CP_ACP,   0,   pFilePathName,   nLen,   lpszFile,   nwLen);
3.wchar转换成char        

   char   *pFilePathName;        

   TCHAR   lpszFile[256];     

   _tcscpy(lpszFile,   _T( "c:\\aa.dll "));
       int   nLen   =   wcslen(wstr)+1;        

   WideCharToMultiByte(CP_ACP,   0,   lpszFile,   nLen,   pFilePathName,   2*nLen,   NULL,   NULL);   

一个完整的例子(网上找的阿,要Ws2_32.lib)

1.#include <windows.h>  
2.#include <stdio.h>  
3.  
4.//function: charTowchar  
5.//purpose:char to WCHAR 、wchar_t、LPWSTR etc  
6.void charTowchar(const char *chr, wchar_t *wchar, int size)  
7.{     
8.    MultiByteToWideChar( CP_ACP, 0, chr,  
9.        strlen(chr)+1, wchar, size/sizeof(wchar[0]) );  
10.}  
11.  
12.//function: wcharTochar  
13.//purpose:WCHAR 、wchar_t、LPWSTR to char  
14.void wcharTochar(const wchar_t *wchar, char *chr, int length)  
15.{  
16.    WideCharToMultiByte( CP_ACP, 0, wchar, -1,  
17.        chr, length, NULL, NULL );  
18.}  
19.  
20.int main (void)  
21.{  
22.    char     chr[128];  
23.    wchar_t  *wchar = L"陈鸿钦";  
24.      
25.  
26.    //wchar_t to char  
27.    wcharTochar(wchar, chr, sizeof(chr));  
28.    printf("char is %s\n", chr);  
29.  
30.    //char to wchar_t  
31.    wchar = (wchar_t *)malloc(sizeof(wchar_t) * 64);  
32.    charTowchar(chr, wchar, sizeof(wchar_t) * 64);  
33.      
34.    wprintf_s(L"%s\n", wchar);//  
35.    getchar();  
36.  
37.    return 0;  
38.}  

  另一个宏:

#include "atlconv.h" 

void func()
 
{
 
 USES_CONVERSION; 

char *test = "i am a sucker";
 
 WCHAR *conv = A2W(strPic1) ;
 
}

  

原文地址:https://www.cnblogs.com/jimson/p/2233727.html