BSTR

BSTR

在头文件中的定义如下:

typedef WCHAR OLECHAR;

typedef OLECHAR *BSTR;

所以BSTR的实际类型其实就是WCHAR*。

在MSDN中的Allocating and Releasing Memory for a BSTR一文中,强调了在使用这个类型时,要在内存上小心对待,以避免发生内存泄露。对于从函数中传出的BSTR,接受的对象要负责对这个BSTR的内存进行管理。在该文中列举了三种情况:

  • 当在一个函数中使用BSTR时,你要负责分配和销毁它,代码如下:

// shows using the Win32 function

// to allocate memory for the string:

BSTR bstrStatus = ::SysAllocString( L"Some text" );

if (bstrStatus == NULL)

   return E_OUTOFMEMORY;

 

pBrowser->put_StatusText( bstrStatus );

// Free the string:

::SysFreeString( bstrStatus );

//...

 

  • 对于从函数中返回的BSTR,要在程序中进行释放

//...

BSTR bstrStatus;

pBrowser->get_StatusText( &bstrStatus );

 

// shows using the Win32 function

// to freee the memory for the string:

::SysFreeString( bstrStatus );

 

如果我们自己定义的函数返回一个BSTR,那么这个BSTR的接收函数应该释放内存。

// Example shows using MFC's

// CString::AllocSysString

 

//...

HRESULT CMyClass::get_StatusText( BSTR * pbstr )

{

   try

   {

      //m_str is a CString in your class

      *pbstr = m_str.AllocSysString( );

      }

   catch (...)

   {

      return E_OUTOFMEMORY;

   }

// The client is now responsible for freeing pbstr.

return( S_OK );

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值