10

Possible Duplicates:
Which is better code for converting BSTR parameters to ANSI in C/C++?
How to convert char * to BSTR?

How I can convert BSTR to const char*?

peterh
  • 11,875
  • 18
  • 85
  • 108
subs
  • 2,189
  • 12
  • 35
  • 59

3 Answers3

11

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.

Community
  • 1
  • 1
Nate
  • 18,752
  • 8
  • 48
  • 54
5
#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.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
0
typedef OLECHAR FAR * BSTR;
typedef WCHAR  OLECHAR;

From here.

WCHAR*. It's a wide char, not a char. This means it's Unicode, not ASCII and shouldn't be converted. If you want to use const char*, don't use wide types.

Although, it is possible using some hackery, you'd possibly lose data as you'll be converting the text from Unicode to ASCII.

Jookia
  • 6,544
  • 13
  • 50
  • 60
  • Narrow character strings do not have to be ASCII. They could be UTF-8 in which case you will still be able to display characters that are typically thought of as wide, e.g. Chinese and Japanese. – CadentOrange Nov 29 '10 at 10:19
  • Some functions don't have an ASCII version. For instance the `Graphics::DrawString`: http://msdn.microsoft.com/en-us/library/ms535991(VS.85).aspx – default Nov 29 '10 at 10:19