CString Char* wchar转换

 

CString 转char *

方法1.直接强制类型转换:

 CString ss="sfasf";
 char *p=(LPSTR)(LPCSTR)ss;

方法二,使用strcpy。例如:

 CString theString( (_T("Char test "));
 LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
 _tcscpy(lpsz, theString);二,使用strcpy。例如:

CString theString( (_T("Char test "));

LPTSTR lpsz = new TCHAR[theString.GetLength()+1];

_tcscpy(lpsz, theString);

 

 

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  

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);

 =   wcslen(wstr)+1;   
      WideCharToMultiByte(CP_ACP,   0,   lpszFile,   nLen,   pFilePathName,   2*nLen,   NULL,   NULL);

 

如果你使用VC2002(2003更好)或以上的话,CString转WCHAR简单的很:

1,假设你的程序是MBCS编译,并且不打算兼容UNICODE的话,那么:

{
        USES_CONVERSION;
       
        CString   sText   =   "text   string ";
        WCHAR   wszWideString[N];

        wcscpy(wszWideString,   CA2CW(sText));
}

2,假设你的程序是UNICODE编译,或者MBCS、UNICODE兼容的话,那么:

{
        USES_CONVERSION;
       
        CString   sText   =   _T( "text   string ");
        WCHAR   wszWideString[N];

        wcscpy(wszWideString,   CT2CW(sText));
}

所以,你应该到MSDN里查询如下关键字即可:

1,   USES_CONVERSION
2,   CA2CW   (会看到一族   X2X   函数)

 

 

 

慎用USES_CONVERSION

USES_CONVERSION是ATL中的一个宏定义。用于编码转换(用的比较多的是CString向LPCWSTR转换)。在ATL下使用要包含头文件#include "atlconv.h"

使用USES_CONVERSION一定要小心,它们从堆栈上分配内存,直到调用它的函数返回,该内存不会被释放。如果在一个循环中,这个宏被反复调用几万次,将不可避免的产生stackoverflow。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值