关于BSTR、_bstr_t详见
《_bstr_t与_variant_t》
。
BSTR转CString
CString转
_bstr_t
CString转 BSTR
注意:用完之后必须使用SysFreeStringBSTR bstr;
CString strSql; bstr = strSql.AllocSysString();
… SysFreeString ( bstrText ); // 用完释放
释放!!!
BSTR bstr = ::SysAllocString(L"Test");
CString strSql; strSql.Empty(); strSql = (LPCSTR)bstr;
或
BSTR bstr = ::SysAllocString(L"Test");
CString str(bstr);
_bstr_t转 CString_bstr_t bstr;
CString strSql; bstr = (_bstr_t)strSql;
_bstr_t bstr;
CString strSql; strSql = (LPCSTR)bstr;
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
;
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
);
本文详细介绍了在编程中如何进行各种字符串类型的转换,包括CString到BSTR、BSTR到CString、BSTR到char*以及char*到BSTR等多种转换方式,并提供了具体的代码示例。

1万+

被折叠的 条评论
为什么被折叠?



