Cstring 與 char*的轉換,TCHAR 與 char 轉換
阿新 • • 發佈:2019-02-14
使用unicode的會存在寬位元組和單位元組之間的轉換:
CString轉char *
1、使用WideCharToMultiByte函式,其中mWcount為CString型別。
char* _wParam = (char*) malloc( sizeof(char) * 10); // = (LPSTR)(LPCTSTR)m_CalibrationData.mWcount;
int len = WideCharToMultiByte(CP_ACP,0,mWcount,mWcount.GetLength()+1,
NULL,0,NULL,NULL );
WideCharToMultiByte(CP_ACP,0,mWcount,mWcount.GetLength()+1,
_wParam,len,NULL,NULL);
2、使用W2A轉換
需要加上標頭檔案:#include <afxpriv.h>
USES_CONVERSION;
_hParam = W2A(mHcount);
3、如果都是單位元組儲存可以直接轉換為char *
char* _hParam = (LPSTR)(LPCTSTR)mHcount;
如果需要將char* 轉CString 以上的方法依然可行。可以使用
A2W()、MultiByteToWideChar()。
TCHAR 轉 char:
_TCHAR* argv[]);
char filename[256];
int iLength ;
//獲取位元組長度
iLength = WideCharToMultiByte(CP_ACP, 0,argv[1], -1, NULL, 0, NULL, NULL);
//將tchar值賦給_char
WideCharToMultiByte(CP_ACP, 0, argv[1], -1, filename, iLength, NULL, NULL);
然後是把char轉為TCHAR
CharToTchar (const char * _char, TCHAR * tchar)
{
int iLength ;
iLength = MultiByteToWideChar (CP_ACP, 0, _char, strlen (_char) + 1, NULL, 0) ;
MultiByteToWideChar (CP_ACP, 0, _char, strlen (_char) + 1, tchar, iLength) ;
}