Condividi tramite


Mediante l'allocazione e il rilascio di memoria per un BSTR

Quando si crea BSTRoggetti che vengono passati tra gli oggetti COM, è necessario richiedere attenzione in modo che la memoria che utilizzano per evitare perdite di memoria.Quando BSTR rimane all'interno di un'interfaccia, è necessario liberare la memoria a quando l'operazione è stata eseguita.Tuttavia, quando BSTR passa da un'interfaccia, l'oggetto ricevente è responsabile della gestione della memoria.

In genere le regole per l'allocazione e il rilascio di memoria allocata per BSTRoggetti sono le seguenti:

  • Quando si chiama una funzione che accetta un argomento BSTR, è necessario allocare memoria per BSTR prima della chiamata e rilasciarlo in seguito.Di seguito è riportato un esempio:

    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);
    }
    
  • Quando si chiama una funzione che restituisce BSTR, è necessario liberare la stringa manualmente.Di seguito è riportato un esempio:

    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);
    
  • Quando si distribuisce una funzione che restituisce BSTR, allocare la stringa ma non libero.La ricezione della funzione liberare memoria.Di seguito è riportato un esempio:

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

Vedere anche

Riferimenti

CStringT::AllocSysString

SysAllocString

SysFreeString

Altre risorse

Stringhe (ATL/MFC)