views:

880

answers:

3

I have a _bstr_t variable bstrErr and I am having a CString variable csError. How do I set the value which come in bstrErr to csError?

+1  A: 

Is it not possible just to cast it:

_bstr_t b("Steve");
CString cs;
cs = (LPCTSTR) b;

I think this should work ok.

YoungPony
Thanks NeeulIts Working
subbu
+1  A: 

If you compile for Unicode - just assign the encapsulated BSTR to the CString. If you compile for ANSI you'll have to use WideCharToMultiByte() for conversion.

Also beware that the encapsulated BSTR can be null which corresponds to an empty string. If you don't take care of this your program will run into undefined behaviour.

sharptooth
A: 

CString has contructors and assignment operators for both LPCSTR and LPCWSTR, so there is never a need to call WideCharToMultiByte, and you can't get the casting wrong in unicode or non-unicode mode.

You can just assign the string this way:

csError = bstrErr.GetBSTR();

Or use the constructor CString csError( bstrErr.GetBSTR() );

I'm using GetBSTR. It's the same thing as casting bstrErr with (LPCWSTR), but I prefer it for legibility.

fredr