zoukankan      html  css  js  c++  java
  • BSTR与char*、cstring、CComBSTR的转换

     1 // BSTR_Convert.cpp : 定义控制台应用程序的入口点。
     2 //
     3 
     4 #include "stdafx.h"
     5 #include <comutil.h>    // _com_util::ConvertBSTRToString
     6 #include <atlbase.h>  //CComBSTR
     7 #include <atlstr.h>
     8 
     9 #pragma comment(lib, "comsuppw.lib")
    10 
    11 using namespace _com_util;
    12 
    13 int _tmain(int argc, _TCHAR* argv[])
    14 {
    15     /******     BSTR->char*    *****/
    16     //方法一使用  ConvertBSTRToString
    17     //BSTR bstrText = ::SysAllocString(L"Test");
    18     //char* lpszText = _com_util::ConvertBSTRToString(bstrText);
    19     //SysFreeString(bstrText);//用完释放
    20     //delete[] lpszText; 
    21     //方法二 使用_bstr_t的赋值运算符重载
    22     //_bstr_t b = bstrText;
    23     //char* lpstrText1 = b;
    24 
    25     /******     char*->BSTR     *****/
    26     //方式一 使用SysAllocString等API函数 
    27     //BSTR bstrText = ::SysAllocString(L"Test");
    28     //BSTR bstrText1 = ::SysAllocStringLen(L"Test1",3); 
    29     //BSTR bstrText2 = ::SysAllocStringByteLen("Test2",4);//乱码
    30     
    31     //方式二 使用COleVariant或_variant   编译出错  属于MFC?无法再WIN32下使用?
    32     //COleVariant strVar("this is a test");
    33     //_variant_t strVar1("this is a test");
    34     //BSTR bstrText = strVar.bstrVal;
    35     //BSTR bstrText1 = strVar1.bstrVal;
    36     
    37     //方式三 方法三,使用_bstr_t,这是一种最简单的方法。
    38     //BSTR bstrText = _bstr_t("This is a test");
    39 
    40     //方法四,使用CComBSTR。例如: 
    41     //BSTR bstrText = CComBSTR("This is a test");
    42     //CComBSTR bstr1("This is a test"); 
    43     //BSTR bstrText1 = bstr1.m_str; 
    44 
    45     //方法五,使用ConvertStringToBSTR。
    46     //char* lpszText = "Test"; 
    47     //BSTR bstrText2 = _com_util::ConvertStringToBSTR(lpszText);
    48 
    49     /******* CString->BSTR *******/
    50     //通 常是通过使用CStringT::AllocSysString来实现
    51     CString cstr("this is a test");
    52     BSTR bstrText = cstr.AllocSysString();
    53     SysFreeString(bstrText);
    54 
    55     /******* BSTR -> CString *******/
    56     //BSTR bstrText = ::SysAllocString(L"Test");
    57     //CString cstr;
    58     //cstr.Empty();
    59     //cstr = bstrText; 
    60     // 或 CStringA str(bstrText);
    61 
    62     system("pause");
    63     return 0;
    64 }
    View Code
  • 相关阅读:
    小Z的袜子
    C#操作XML
    C#中接口的实现方法
    C#邮箱批量注册
    C# 委托的使用
    C# socket
    在C#.net中如何操作XML
    C#接口的基础知识
    C#判断网页中是否含有某字符串
    C#多线程处理多个队列的数据
  • 原文地址:https://www.cnblogs.com/lisuyun/p/3628921.html
Copyright © 2011-2022 走看看