几何尺寸与公差论坛

 找回密码
 注册
查看: 2098|回复: 0

【转帖】分配和释放 Bstr 的内存

[复制链接]
发表于 2008-12-18 09:59:30 | 显示全部楼层 |阅读模式
当创建 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 );
  • }
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|Archiver|小黑屋|几何尺寸与公差论坛

GMT+8, 2024-4-25 09:27 , Processed in 0.037194 second(s), 19 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表