您的位置:首页 > 其它

BSTR与char*、cstring、CComBSTR的转换

2014-03-27 18:05 435 查看
// BSTR_Convert.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <comutil.h>    // _com_util::ConvertBSTRToString
#include <atlbase.h>  //CComBSTR
#include <atlstr.h>

#pragma comment(lib, "comsuppw.lib")

using namespace _com_util;

int _tmain(int argc, _TCHAR* argv[])
{
/******     BSTR->char*    *****/
//方法一使用  ConvertBSTRToString
//BSTR bstrText = ::SysAllocString(L"Test");
//char* lpszText = _com_util::ConvertBSTRToString(bstrText);
//SysFreeString(bstrText);//用完释放
//delete[] lpszText;
//方法二 使用_bstr_t的赋值运算符重载
//_bstr_t b = bstrText;
//char* lpstrText1 = b;

/******     char*->BSTR     *****/
//方式一 使用SysAllocString等API函数
//BSTR bstrText = ::SysAllocString(L"Test");
//BSTR bstrText1 = ::SysAllocStringLen(L"Test1",3);
//BSTR bstrText2 = ::SysAllocStringByteLen("Test2",4);//乱码

//方式二 使用COleVariant或_variant   编译出错  属于MFC?无法再WIN32下使用?
//COleVariant strVar("this is a test");
//_variant_t strVar1("this is a test");
//BSTR bstrText = strVar.bstrVal;
//BSTR bstrText1 = strVar1.bstrVal;

//方式三 方法三,使用_bstr_t,这是一种最简单的方法。
//BSTR bstrText = _bstr_t("This is a test");

//方法四,使用CComBSTR。例如:
//BSTR bstrText = CComBSTR("This is a test");
//CComBSTR bstr1("This is a test");
//BSTR bstrText1 = bstr1.m_str;

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

/******* CString->BSTR *******/
//通 常是通过使用CStringT::AllocSysString来实现
CString cstr("this is a test");
BSTR bstrText = cstr.AllocSysString();
SysFreeString(bstrText);

/******* BSTR -> CString *******/
//BSTR bstrText = ::SysAllocString(L"Test");
//CString cstr;
//cstr.Empty();
//cstr = bstrText;
// 或 CStringA str(bstrText);

system("pause");
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: