分配时在cstring中崩溃 [英] Crashing in cstring when assigning

查看:107
本文介绍了分配时在cstring中崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 from VARIANT (VARIANT and VARIANTARG Data Types [Automation][^]) which is just a union.

So you must check the vt member and access the matching data field only. If your olevar contains a double (vt is VT_R8), the corresponding field is dblVal. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆