CString、wchar和char相互转换(转载)
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);
char*和CString转换
CString 是一种很特殊的 C++ 对象,它里面包含了三个值:一个指向某个数据缓冲区的指针、一个是该缓冲中有效的字符记数(它是不可存取的,是位于 CString 地址之下的一个隐藏区域)以及一个缓冲区长度。有效字符数的大小可以是从0到该缓冲最大长度值减1之间的任何数(因为字符串结尾有一个NULL字符)。字符记数和缓冲区长度被巧妙隐藏。
(1) char*转换成CString
若将char*转换成CString,除了直接赋值外,还可使用CString::Format进行。例如:
         char chArray[] = "Char test";
         TCHAR * p = _T("Char test");( 或LPTSTR p = _T("Char test");)
         CString theString = chArray;
         theString.Format(_T("%s"), chArray);
         theString = p;
(2) CString转换成char*
若将CString类转换成char*(LPSTR)类型,常常使用下列三种方法:
方法一,使用强制转换。例如:
       CString theString( (_T("Char test "));
        LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;
方法二,使用strcpy。例如:
       CString theString( (_T("Char test "));
       LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
        _tcscpy(lpsz, theString);
需要说明的是,strcpy(或可移值的_tcscpy)的第二个参数是 const wchar_t* (Unicode)或const char* (ANSI),系统编译器将会自动对其进行转换。
方法三,使用CString::GetBuffer。
        如果你需要修改 CString 中的内容,它有一个特殊的方法可以使用,那就是 GetBuffer,它的作用是返回一个可写的缓冲指针。 如果你只是打算修改字符或者截短字符串,例如:
       CString s(_T("Char test "));
        LPTSTR p = s.GetBuffer();
LPTSTR dot = strchr(p, ''.'');
// 在这里添加使用p的代码
if(p != NULL)
         *p = _T('\0');
         s.ReleaseBuffer();                     // 使用完后及时释放,以便能使用其它的CString成员函数
在 GetBuffer 和 ReleaseBuffer 之间这个范围,一定不能使用你要操作的这个缓冲的 CString 对象的任何方法。因为 ReleaseBuffer 被调用之前,该 CString 对象的完整性得不到保障。
                    
                
                
            
        
浙公网安备 33010602011771号