Use a temporary variable of the type '_bstr_t' to wrap the 'BSTR'. This way you handle both the 208 and make sure that you have no memory leak:
_bstr_t tmp(bstr, FALSE); //wrap the BSTR
CString cs(static_cast<const char*>(tmp)); //convert it
AfxMessageBox(cs, MB_OK, 0);
// when tmp goes out of scope it will free the BSTRs memory
Note, that this won't work in a UNICODE build.
Last edited by Andreas Masur; July 24th, 2005 at 06:48 AM.
Re: MFC String: How to convert between a 'CString' and a 'BSTR'?
This statement is incorrect: "If you pass the BSTR to some OLE function, this will normally free the BSTRs memory when done with it."
The general rule to COM resource is, if you allocate it then you release it. The only exception is when a value is passed over a COM interface as an OUT param. In that case, the receiver of the value is responsible for releasing the resource.
This sort of mistake is particularly onerous because the memory leaked is not associated with the process that leaked it. The only way that this leak is recovered is by reboot of the system.
Last edited by Andreas Masur; July 24th, 2005 at 06:49 AM.