zoukankan      html  css  js  c++  java
  • 分配和释放 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 );
      }
      //...
  • 相关阅读:
    time模块
    Python进程模块
    Django面试题
    基本命令行语句
    scrapy中的配置与中间件
    JSON编码于解码对应dump于load
    python操作数据库
    Python里的方法
    正则表达式
    Python常用模块
  • 原文地址:https://www.cnblogs.com/zhb/p/2671329.html
Copyright © 2011-2022 走看看