分配和释放 BSTR 的内存

 【转自】http://www.cnblogs.com/xiaotaoliang/archive/2005/08/26/223069.html

 

当创建 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 );
    }
    //...
posted @ 2012-09-05 09:28  B.Zhou  阅读(279)  评论(0编辑  收藏  举报