CComBSTR Basics
This section describes common usage of the CComBSTR smart data type.
Returning a BSTR
Section titled “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.
HRESULT Acme4321::IAcme4321Display_get_Text(BSTR* val){ HRESULT hr = S_OK;
CComBSTR 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 CopyTo, 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.
class Acme4321{... CComBSTR m_bstrText;};
HRESULT Acme4321::IAcme4321Display_get_Text(BSTR* val){ HRESULT hr = S_OK;
// Copy the string hr = m_bstrText.CopyTo(val);
return hr;}
ReceivingReceiving a BSTR
Section titled “Receiving a BSTR”When a client application calls a driver that returns a BSTR, the client must free the BSTR that is allocated by the driver.
void main(){ // Initialize COM, create instance of object...
CComBSTR bstrText; hr = pDriver->get_Text(&bstrText); if (SUCCEEDED(hr)) { // 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 CComBSTR.