Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert BSTR to const char* [duplicate]

Tags:

c++

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*?

like image 279
subs Avatar asked Nov 29 '10 09:11

subs


2 Answers

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.

like image 55
Nate Avatar answered Oct 14 '22 12:10

Nate


#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.

like image 26
Steve Townsend Avatar answered Oct 14 '22 10:10

Steve Townsend