Click or drag to resize

BSTR Basics

This topic describes common usage of the BSTR data type. It is generally easier to use smart data types rather than using BSTR directly. For more information on the smart data types, see _bstr_t Basics, CComBSTR Basics, and CString Basics.

Allocating 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;

  // Allocate a BSTR with a fixed string  
  *val = ::SysAllocString(OLESTR("Hello world."));
  if (*val == NULL)
  {
    hr = ReportError(IDS_E_IVI_OUT_OF_MEMORY);
  }

  return hr;
}
Freeing 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++
// MyClient.cpp
void main()
{
  // Initialize COM, create instance of object...

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

    // Free the string
    ::SysFreeString(bstrText);
  }

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

When implementing a method that should return a BSTR, as [in, out], the BSTR should be freed by the server before allocating a new one. The new BSTR is then freed by the client.

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

  // Do something with the string that is passed in

  // ...

  // Free the string that is passed in
  ::SysFreeString(*val);

  // Allocate a BSTR with a fixed string  
  *val = ::SysAllocString(OLESTR("Hello world."));
  if (*val == NULL)
  {
    hr = ReportError(IDS_E_IVI_OUT_OF_MEMORY);
  }

  return hr;
}
See Also

Other Resources

Download a complete CHM version of this documentation here.