zoukankan      html  css  js  c++  java
  • 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) ;
     
    }
    

      

  • 相关阅读:
    [转]Android Uri Intent 用法汇总
    [书目20120607]编写高质量代码:改善C#程序的157个建议
    [转]Android多媒体:实现图像的编辑和合成
    [转]Android IPC进程通信——Messager方式
    [转]Android中程序与Service交互的方式——交互方式
    [书目20120605]人力资源管理 余凯成
    [转]SurfaceView horizontal scrolling
    住房乃生活所需
    [转]android service 学习(上) 音乐播放
    [转]Android实现获取本机中所有图片
  • 原文地址:https://www.cnblogs.com/jimson/p/2233727.html
Copyright © 2011-2022 走看看