MFC CString 與常用型態互轉(int,LONG,LONGLONG,BYTE*,LPWSTR,BSTR,CComBSTR,char*,unsigned char*)
MFC CString 與常用型態互轉(int,LONG,LONGLONG,BYTE*,LPWSTR,BSTR,CComBSTR,char*,unsigned char*)
資料來源:http://ascii-iicsa.blogspot.tw/2010/09/cstring.html
CString to int
CString strSource;
int n = _ttoi(strSource);
CString to LONG
CString strSource;
int n = _ttol(strSource);
CString to double
CString strSource;
double dbl = _tstof((LPTSTR)(LPCTSTR)strSource);
// 或是有些平台上沒有 _tstof 就要先轉成 ansi 再用 atof 來轉
int nIndexTemp = WideCharToMultiByte(CP_ACP, 0, strSource, -1, NULL, 0, NULL, NULL);
char *pAnsi = (char*)malloc(nIndexTemp + 1);
ZeroMemory(pAnsi, nIndexTemp + 1);
WideCharToMultiByte(CP_ACP, 0, strSource, -1, pAnsi, nIndexTemp, NULL, NULL);
double dbl = atof(pAnsi);
free(pAnsi);
CString to LONGLONG
CString strSource;
LONGLONG ll = _ttoi64(strSource);
LONGLONG to CString
CString strData;
strData.format(_T(“%I64d”), ll);
CString to BYTE*
CString strSource;
BYTE* pbt = (BYTE*)(T2A((LPTSTR)(LPCTSTR)strSource);
// 或有特殊需求可使用 strdup 複製一份,但要記得自己 free 掉
(BYTE*)strdup(T2A((LPTSTR)(LPCTSTR) strContentKey));
CString to char*
#include <afxpriv.h>
/*
USES_CONVERSION是ATL中的一个宏定义。用于编码转换(用的比较多的是CString向LPCWSTR转换)。在ATL下使用要包含头文件#include “atlconv.h”
使用USES_CONVERSION一定要小心,它们从堆栈上分配内存,直到调用它的函数返回,该内存不会被释放。如果在一个循环中,这个宏被反复调用几万次,将不可避免的产生stackoverflow。
*/
USES_CONVERSION;//使用 ATL 3.0 巨集
CString strSource;
char* psz = T2A((LPTSTR)(LPCTSTR)strSource);
CString to unsigned char*
CString str;
unsigned char *ptr2 = (unsigned char*)str.GetBuffer(0);
BYTE* to CString
BYTE* pBuf;
CString str = W2T((LPWSTR)pBuf);
CString to TCHAR*
CString strSource;
TCHAR *ptc = (TCHAR*)T2W((LPTSTR)(LPCTSTR)strSource);
// 或
TCHAR *ptc = (LPTSTR)(LPCTSTR)strSource;
CString to CComBSTR
CString strSource;
CComBSTR bstrSS(strSource);
BSTR to CString
BSTR bstrText;
CString strData;
strData = bstrText;
CString to LPWSTR
CString strSource;
LPWSTR lstr = (LPWSTR)(LPCTSTR)strSource;