分配时在cstring中崩溃 [英] Crashing in cstring when assigning
问题描述
COleVariant olevar;
rst.GetFieldValue(a,olevar);
CString str =(LPCTSTR)olevar.bstrVal;(carhing)
$ / $
它在str中崩溃..
当olevar有双倍价值时。请告诉我为什么会崩溃。
我尝试过的事情:
COleVariant olevar;
rst.GetFieldValue(a,olevar);
CString str =(LPCTSTR)olevar.bstrVal;(carhing)
COleVariant olevar;
rst.GetFieldValue(a, olevar);
CString str = (LPCTSTR)olevar.bstrVal;(carshing)
it is crashing in the str ..
when olevar is having double value. please let me know why it is crashing.
What I have tried:
COleVariant olevar;
rst.GetFieldValue(a, olevar);
CString str = (LPCTSTR)olevar.bstrVal;(carshing)
推荐答案
COleVariant
派生自VARIANT
( VARART和VARIANTARG数据类型[自动化] [ ^ ])这只是一个union
。
因此,您必须检查vt
成员并仅访问匹配的数据字段。如果olevar
包含double
(vt
VT_R8
),相应的字段是dblVal
。访问任何其他字段可能会导致错误的值或未定义的行为。
您可以自己进行转换:
COleVariant
is derived fromVARIANT
(VARIANT and VARIANTARG Data Types [Automation][^]) which is just aunion
.
So you must check thevt
member and access the matching data field only. If yourolevar
contains adouble
(vt
isVT_R8
), the corresponding field isdblVal
. Accessing any other fields may result in wrong values or undefined behaviour.
You can do the conversion yourself:
CString str;
if (oleVar.vt == VT_R8)
str.Format(_T("%E"), oleVar.dblVal);
另一种选择是使用<转换变体类型a href =https://msdn.microsoft.com/en-us/library/5yw15s7x.aspx> COleVariant :: ChangeType [ ^ ]:
Another option is converting the variant type using COleVariant::ChangeType[^]:
oleVar.ChangeType(VT_BSTR);
CString str = oleVar.bstrVal;
另请注意,在 LPCTSTR
中没有使用任何转换上面的例子。 BSTR
始终是Unicode,上面的赋值会在转换为 LPCTSTR
时将字符串转换为带有非Unicode构建的ANSI不适用于非Unicode构建(它只复制第一个字符)。
Note also that no casting to LPCTSTR
is used in the above example. BSTR
is always Unicode and the above assignment will convert the string to ANSI with non-Unicode builds while casting to LPCTSTR
would not work with non-Unicode builds (it would copy only the first character).
这篇关于分配时在cstring中崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!