Converting BSTR to string and vice versa

Could anyone tell me how to convert BSTR to string and vice versa?
Also, how can I convert between BSTR and CString?
csoundAsked:
Who is Participating?
 
lakshman_ceConnect With a Mentor Commented:
1. You can convert at CString to a BSTR by calling the CString method AllocSysString:
CString s;
s = ... ; // whatever
BSTR b = s.AllocSysString();
 The pointer b points to a newly-allocated BSTR object which is a copy of the CString, including the terminal NUL character. This may now be passed to whatever interface you are calling that requires a BSTR. Normally, a BSTR is disposed of by the component receiving it. If you should need to dispose of a BSTR, you must use the call
::SysFreeString(b);
to free the string.

2. For BSTR to CString you can also refer to this link
http://www.codeguru.com/Cpp/Cpp/string/conversions/article.php/c5639/

0
 
AlexFMConnect With a Mentor Commented:
You can use _bstr_t class. _bstr_t instance can be created from BSTR pointer, and casted to char* and wchar_t*.

void Foo(BSTR bstr)
{
    _bstr_t b(bstr, false);

    const char* pChar = (const char*)b;
    const wchar_t* pWChar = (const wchar_t*)b;
}

CString can be created from char*/wchar_t*. If BSTR is kept in VARIANT, you can use const VARIANT& constructor.
0
 
AlexFMCommented:
Without questioner's reply, I suggest split.
0
 
csoundAuthor Commented:
I'm sorry for such a late reply. Thank you all for your helps.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.