1. 程式人生 > >C++字元型別轉換(BSTR、_bstr_t與CString、char *轉換)

C++字元型別轉換(BSTR、_bstr_t與CString、char *轉換)

1、CString轉BSTR

BSTR bstr;
CString strSql; 
bstr = strSql.AllocSysString();
… 
SysFreeString(bstrText); // 用完釋放 

注意:用完之後必須使用SysFreeString 釋放!!!

2、BSTR轉CString

//方法一
BSTR bstr = ::SysAllocString(L"Test"); 
CString strSql; 
strSql.Empty(); 
strSql = (LPCSTR)bstr;

//方法二
BSTR bstr = ::SysAllocString(L"Test"); 
CString str(bstr);

3、CString轉_bstr_t

_bstr_t bstr;
CString strSql; 
bstr = (_bstr_t)strSql;

4、_bstr_t轉CString

_bstr_t bstr;
CString strSql; 
strSql = (LPCSTR)bstr;

5、BSTR轉char*

//方法一,使用ConvertBSTRToString
BSTR bstrText = ::SysAllocString(L"Test"); 
char* lpszText2 = _com_util::ConvertBSTRToString(bstrText); 
SysFreeString(bstrText); // 用完釋放 
delete[] lpszText2; 

//方法二,使用_bstr_t的賦值運算子過載
_bstr_t b = bstrText; 
char* lpszText2 = b; 

6、char*轉換成BSTR

//方法一,使用SysAllocString等API函式
BSTR bstrText = ::SysAllocString(L"Test"); 
BSTR bstrText = ::SysAllocStringLen(L"Test",4); 
BSTR bstrText = ::SysAllocStringByteLen("Test",4); 

//方法二,使用COleVariant或_variant_t
//COleVariant strVar("This is a test"); 
_variant_t strVar("This is a test"); 
BSTR bstrText = strVar.bstrVal; 

//方法三,使用_bstr_t,這是一種最簡單的方法
BSTR bstrText = _bstr_t("This is a test");

//方法四,使用CComBSTR
BSTR bstrText = CComBSTR("This is a test"); 
//或
CComBSTR bstr("This is a test"); 
BSTR bstrText = bstr.m_str;

//方法五,使用ConvertStringToBSTR
char* lpszText = "Test"; 
BSTR bstrText = _com_util::ConvertStringToBSTR(lpszText);