![]() | 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.
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.
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; }
When a client calls a driver that returns a BSTR, the client must free the BSTR that is allocated by the driver.
// 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.
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; }