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 );
}