convert BSTR to const char*

A BSTR is actually a WCHAR* with a length prefix. The BSTR value points to the beginning of the string, not to the length prefix (which is stored in the bytes just “before” the location pointed to by the BSTR).

In other words, you can treat a BSTR as though it is a const WCHAR*. No conversion necessary.

So your question is really: “How can I convert a Unicode string (WCHAR*) to a char*?” and the answer is to use the ::WideCharToMultiByte API function as explained here. Or, if you are using MFC/ATL in your application, use the ATL and MFC Conversion Macros.


#include "comutil.h"

BSTR bstrVal;
_bstr_t interim(bstrVal, false);    
    // or use true to get original BSTR released through wrapper
const char* strValue((const char*) bstrVal);

This handles all the Wide Char to multibyte conversion.

Tags:

C++