
Converting from BSTR to CString
In Visual C++ 6.0, it was acceptable to use the following code:
BSTR bstr = SysAllocString(L"Hello");
CString str = bstr;
SysFreeString(bstr);
With new projects under Visual C++ .NET, this will cause the following error under ANSI builds:
error C2440: 'initializing' : cannot convert from 'BSTR' to
'ATL::CStringT<BaseType,StringTraits>'
There are now UNICODE and ANSI versions of CString (CStringW and CStringA). To flag any unnecessary overhead incurred by implicit conversions, constructors that take the inverse type (for example, CStringA taking a UNICODE argument, or CStringW taking an ANSI argument) are now tagged as explicit using the following entry in stdafx.h:
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS
To work around this error, do one of the following:
-
Use CStringW to avoid conversion:
BSTR bstr = SysAllocString(L"Hello");
CStringW str = bstr;
SysFreeString(bstr);
-
Explicitly call the constructor:
BSTR bstr = SysAllocString(L"Hello");
CString str = CString(bstr);
SysFreeString(bstr);
-
Remove the line #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS from stdafx.h.