我搜集的C++字符类型的相互转换

基本类型 char*,int,wchar_t,BSTR,VARIANT
封装类型 string,CString,_bstr_t,CComBSTR,_variant_t,COleVariant


char* to int,long,double
atoi(char*),atol(char*),atof(char*)

int to char*,long to char*
itoa(i,char*,进制),ltoa(l,char*,进制); 

wchar_t to const char
W2CA()

char to const wchar_t
A2CW()

wchar_t to char
W2A()

char to wchar_t
A2W()

CString to string
例子:
CString a = "xyz";
string b = a.GetBuffer(0);

string to CString
例子:
string a = "xyz";
CString b = a.c_str();

const char* to char*
通过使用(LPSTR)(LPCTSTR); 
 
BSTR to char*

通过使用_com_util::ConvertBSTRToString(BSTR pSrc);  

char* to BSTR

通过使用_com_util::ConvertStringToBSTR(const char *pSrc);

_variant_t to others

通过使用VariantChangeType(&var,&var,0,VT_XXXX);  

char* to _variant_t
例子:
_variant_t x = (_bstr_t)"姓名";

BSTR to VARIANT
例子:
BSTR x = SysAllocString(L"Hello");  
VARIANT myVariant;   myVariant.vt = VT_BSTR;  
myVariant.bstrVal = x;  
SysFreeString(x); 

CString to VARIANT
例子:
CString   myCString(_T("My String"));  
CString   mySecondString;   
USES_CONVERSION;  
BSTR y = SysAllocString(T2COLE(myCString));  
myVariant.bstrVal = y;  
mySecondString = y;  
SysFreeString(y);  

CString to BSTR--------------通过使用CStringT::AllocSysString()
例子:
CString str("This is a test");
BSTR bstrText = str.AllocSysString();

SysFreeString(bstrText);

BSTR to CString--------------通过使用::SysAllocString(wchar_t);
例子:
BSTR bstrText = ::SysAllocString(L"Test");
CStringA str;
str.Empty();
str = bstrText; 
SysFreeString(bstrText);  

_bstr_t to CString
通过使用_com_util::ConvertBSTRToString(bstr);

CString to _bstr_t
通过使用_com_util::ConvertStringToBSTR(const char*);

 

你可能感兴趣的:(我搜集的C++字符类型的相互转换)