Click or drag to resize

String Converter Classes

This sections describes common usage of the string converter classes.

Converting from a BSTR

The converter class COLE2T can be used to convert from a BSTR to an LPCTSTR.

C++
void PrintMessage(LPCTSTR pszText)
{
  // Do something with the LPCTSTR  
}

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

  // Use COLE2T to pass in a LPCTSTR
  PrintMessage(COLE2T(val));

  return hr;
}

Do not attempt to use a LPCTSTR obtained from a COLE2T after the COLE2T goes out of scope as the memory will be deleted. For this reason, COLE2T is typically used to pass a BSTR to a function that accepts an LPCTSTR or to initialize a string data type that will make a copy of the LPCTSTR immediately.

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

  // CString will make a copy of the LPCTSTR, this is ok.
  CString strText = COLE2T(val);

  return hr;
}

It is important to cast the COLE2T object to LPCTSTR when calling a function with variable arguments, if the variable argument is expected to be of type LPCTSTR. The most common example is CString::Format when the argument type is specified as %s.

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

  // IMPORTANT: Must cast the COLE2T object to LPCTSTR in this case!
  CString strText;
  strText.Format(_T("\"%s\""), LPCTSTR(COLE2T(val)));

  return hr;
}

Download a complete CHM version of this documentation here.