共用方式為


配置和釋放 BSTR 的記憶體。

當您建立 BSTR個並將它們用於避免記憶體流失的它們在 COM 物件時,您必須注意視為在記憶體中。 當 BSTR 介面內時,您必須釋放它的記憶體,當您完成使用後。 不過,在中,當 BSTR 透過介面之外,接收的物件負責其記憶體管理的責任。

一般而言,配置及釋放供 BSTR配置之記憶體的規則如下:

  • 當您呼叫需要指標 BSTR 引數的函式時,您必須在呼叫之前 BSTR 配置的記憶體後釋放它。 例如:

    HRESULT CMyWebBrowser::put_StatusText(BSTR bstr)
    
    // shows using the Win32 function 
    // to allocate memory for the string: 
    BSTR bstrStatus = ::SysAllocString(L"Some text");
    if (bstrStatus != NULL)
    {
       pBrowser->put_StatusText(bstrStatus);
       // Free the string:
       ::SysFreeString(bstrStatus);
    }
    
  • 當您呼叫會傳回 BSTR的函式時,您必須釋放字串。 例如:

    HRESULT CMyWebBrowser::get_StatusText(BSTR* pbstr)
    
    BSTR bstrStatus;
    pBrowser->get_StatusText(&bstrStatus);
    
    // shows using the Win32 function 
    // to free the memory for the string: 
    ::SysFreeString(bstrStatus);
    
  • 當您實作會傳回 BSTR的函式時,將字串,但不要釋放它。 接收函式釋放記憶體。 例如:

    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);
    }
    

請參閱

參考

CStringT::AllocSysString

SysAllocString

SysFreeString

其他資源

字串 (來源)