查看单个帖子
旧 2008-12-18, 09:59 AM   #1
huangyhg
超级版主
 
huangyhg的头像
 
注册日期: 04-03
帖子: 18592
精华: 36
现金: 249466 标准币
资产: 1080358888 标准币
huangyhg 向着好的方向发展
默认 【转帖】分配和释放 Bstr 的内存

当创建 BSTR 并在 COM 对象之间传递它们时,必须小心地处理它们所使用的内存以避免内存泄漏。当 BSTR 停留在接口中时,在完成其使用后必须释放出它的内存。但是,如果 BSTR 传递出了接口,那么接收对象将负责它的内存管理。

一般情况下,分配和释放分配给 BSTR 的内存的规则如下,
这个规则也适用于自定义对象的内存分配与释放规则:
  • 当一个函数的参数是传值进来需要 BSTR 类型时,必须在调用之前为 BSTR 分配内存,并且在完成操作之后将其释放。
  • 例如:
  • HRESULT IWebBrowser2::put_StatusText( 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 参数用传址方式时,函数内部自己定义, 必须自己来释放字符串。例如:
    HRESULT IWebBrowser2::get_StatusText( BSTR FAR* pbstr );
    //...
    BSTR bstrStatus;
    pBrowser->get_StatusText( &bstrStatus );

    // shows using the Win32 function to freee the memory for the string:
    ::SysFreeString( bstrStatus );
  • 当函数实现返回类型为 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 );
  • }
__________________
借用达朗贝尔的名言:前进吧,你会得到信心!
[url="http://www.dimcax.com"]几何尺寸与公差标准[/url]
huangyhg离线中   回复时引用此帖
GDT自动化论坛(仅游客可见)