Click or drag to resize

_bstr_t Basics

This topic describes common usage of the _bstr_t smart data type.

Returning a BSTR

When implementing a method that should return a BSTR, either as [out, retval], [in, out] or [out], the BSTR should be allocated by the driver and freed by the client application.

C++
HRESULT Acme4321::IAcme4321Display_get_Text(BSTR* val)
{
  HRESULT hr = S_OK;

  _bstr_t bstrText(_T("Hello world."));

  // Assign the internal BSTR while transfering ownership  
  *val = bstrText.Detach();

  return hr;
}

Although using Detach is preferred (it doesn't allocate a new BSTR unnecessarily), it is sometimes more appropriate to use copy, as in the following example. Since the string we want to return is kept in a member variable, we do not want the internal BSTR ownership transferred to the caller.

C++
class Acme4321
{
...
  _bstr_t m_bstrText;
};

HRESULT Acme4321::IAcme4321Display_get_Text(BSTR* val)
{
  HRESULT hr = S_OK;

  // Copy the string
  *val = m_bstrText.copy();

  return hr;
}
Receiving a BSTR

When a client calls a driver that returns a BSTR, the client must free the BSTR that is allocated by the driver.

C++
void main()
{
  // Initialize COM, create instance of object...

  _bstr_t bstrText;
  hr = pDriver->get_Text(bstrText.GetAddress());
  if (SUCCEEDED(hr))
  {
    // Do something with the string that is received...
  }

  // String will be freed by the destructor

  // Release instance of object, terminate COM...
}

When using #import with wrapper interfaces and smart data types, it is even easier to use properties or methods that return a BSTR, as the signatures in the wrapper interfaces are changed to use _bstr_t instead of BSTR.

C++
void main()
{
  // Initialize COM, create instance of object...

  // _com_error exception will be thrown if this fails
  _bstr_t bstrText = pDriver->Text;

  // Do something with the string that is received...

  // String will be freed by the destructor

  // Release instance of object, terminate COM...
}

More information is available in the MSDN documentation for _bstr_t.

See Also

Other Resources

Download a complete CHM version of this documentation here.