Tech Support > Microsoft Windows > Development Resources > std::string out of a BSTR
std::string out of a BSTR
Posted by Boogie El Aceitoso on December 2nd, 2003


Hi,

How can I get an std::string (not std::wstring) out of a BSTR? I need to
convert a BSTR to single byte encoding.

Thanks

Posted by Craig Kelly on December 2nd, 2003


You can convert a BSTR to a char* with WideCharToMultiByte and initialize
the std::string from there. Just keep in mind that in many environments
(including VB) a NULL BSTR and an zero length BSTR are equivalent.

If you don't mind using the COM "helpers" in VC, you can also use _bstr_t
which has a char* operator that does the conversion for you (typed in email,
so not checked):

std::string bstr2std(_bstr_t b)
{
char* c = b;
if (b)
return c;
else
return "";
}

Craig

"Boogie El Aceitoso" <frr149@telefonica.net> wrote:


Posted by Bob Bradley on December 2nd, 2003


In article <r61psvcgfbumlv24nubur5ij675qpmdjnk@4ax.com>,
Boogie El Aceitoso <frr149@telefonica.net> wrote:

You can use WideCharToMultiByte( CP_UTF8, ... ) to convert to
std::string.