Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

BSTR to String

Status
Not open for further replies.

conor0callaghan

Programmer
Mar 18, 2002
20
0
0
IE
He I want to convert a BSTR to a string so I can cout<< the bstr.
Can anyone help?
 
use
wcout<< theBstr<< ...

Ion Filipski
1c.bmp
 
1) Assuming you are doing so in a console application, you can also use the ATL conversion macros:

#include <atlbase.h>
#include <atlconv.h>

...
int main()
{
USES_CONVERSION; // this is necessary

BSTR strHello = SysAllocString(L&quot;Hello&quot;);

std::cout<<OLE2CA(strHello)<<std::endl;

SysFreeString(strHello);

return 0;
}

2) If you don't want ATL headers, you can use VC++ runtime support for COM this way.

...
#include <comdef.h>

int main()
{
BSTR strHello = SysAllocString(L&quot;Hello&quot;);

_bstr_t bstrHello(strHello, true); // passing true means
// you should not call
// SysFreeString

std::cout<<LPCSTR(bstrHello)<<std::endl;

return 0;
}

Cheers,
Andy
 
Wow, that was a painful FAQ to read. May I suggest at least a spell-check?
 
>teriviret
I'm not a native english speaker, but the FAQ I've written really helps. I think is easier to look in the sample from the FAQ than to look for syntactical errors [LOL]. The FAQ is written quite three years ago, but you're the first complaining on spelling. But I'll check for errors. I hope the errors are not in the C++ code :).

Ion Filipski
1c.bmp
 
Sorry, I meant no disrespect, but I found it hard to read. But then again I've been getting used to reading Microsoft on-line help, so I guess my brain may be a little warped. :)

It is nice to see some example code, as Microsoft help is often devoid of it right when you'd need it. May I make one small suggestion though -- on the lines in your example code where you output something, it would help to include what is actually printed, in a comment next to the code.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top