梁某人

发展才是硬道理

导航

分配和释放 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 );
    }
    //...

posted on 2005-08-26 01:19  涛仔28  阅读(1572)  评论(0编辑  收藏  举报