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
?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
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.
CStringT
,CString
,CStringA
, andCStringW
:CStringT
is a complicated class template based on an arbitrary character type and helper class templates for managing the storage and the features.CString
is a typedef of the template class that uses theTCHAR
character type.TCHAR
is a generic type that resolves towchar
if the macroUNICODE
is set, else tochar
.CStringA
is a typedef of the template class that uses internally the narrow character typechar
.CStringW
is a typedef of the template class that uses internally the wide character typewchar_t
.I never use
CString
in code, instead I always use the explicit classesCStringA
orCStringW
. The classesCString*
have constructors that accept narrow and wide strings. The same is true for_bstr_t
. Strings of typeBSTR
must be allocated by the functionSysAllocString()
that expects anOLECHAR
string, hence in Win32/64 a wide string. If you want to copy a_bstr_t
that contains Unicode to aCStringA
you must convert it to UTF8. I use the classesCW2A
andCA2W
for conversion.In the following event function of a Word add-in, I show the use of these types:
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.
Is it not possible just to cast it:
I think this should work when the project is Unicode.