在C ++中转换为/从VARIANT类型转换的简单方法 [英] A simple way to convert to/from VARIANT types in C++

查看:85
本文介绍了在C ++中转换为/从VARIANT类型转换的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何易于使用高级类或库,可让您与Visual C ++中的VARIANT进行交互?

Are there any easy-to-use, high-level classes or libraries that let you interact with VARIANTs in Visual C++?

更具体地说,我想在POD类型(例如doublelong),字符串(例如CString)以及容器(例如std::vector)和VARIANT之间进行转换.例如:

More specifically, I'd like to convert between POD types (e.g. double, long), strings (e.g. CString), and containers (e.g. std::vector) and VARIANTs. For example:

long val = 42;
VARIANT var;
if (ToVariant(val, var)) ...     // tries to convert long -> VARIANT
comObjPtr->someFunc(var);

std::vector<double> vec;
VARIANT var = comObjPtr->otherFunc();
if (FromVariant(var, vec)) ...   // tries VARIANT -> std::vector<double>

我(天真吗?)假设与COM一起工作的人们一直在这样做,因此很可能会有一个单个方便的库来处理各种转换.但是我所能找到的只是各种各样的包装器类,它们各自转换几种类型:

I (naively?) assumed that people working with COM do this all the time, so there would most likely be a single convenient library that handles all sorts of conversions. But all that I've been able to find is a motley assortment of wrapper classes that each convert a few types:

  • _variant_t or CComVariant for POD types
  • _bstr_t, CComBSTR, or BSTR for strings
  • CComSafeArray or SAFEARRAY for arrays

是否有任何简单的方法-无需切换到Visual Basic-即可避免这种尴尬的内存管理和按位VT_ARRAY | VT_I4代码的噩梦?

Is there any simple way -- short of switching to Visual Basic -- to avoid this nightmare of awkward memory management and bitwise VT_ARRAY | VT_I4 code?

相关问题:

  • CComVariant vs. _variant_t, CComBSTR vs. _bstr_t
  • Convert VARIANT to...?
  • How to best convert VARIANT_BOOL to C++ bool?

推荐答案

好吧,使用各种包装器类已经为您完成了大部分艰苦的工作.我更喜欢_variant_t和_bstr_t,因为它们更适合于POD类型和字符串之间的转换.对于简单数组,您真正需要的只是模板转换功能.类似于以下内容:

Well, most of the hard work is already done for you with the various wrapper classes. I prefer _variant_t and _bstr_t as they are more suited for conversion to/from POD types and strings. For simple arrays, all you really need is template conversion function. Something like the following:

// parameter validation and error checking omitted for clarity
template<typename T>
void FromVariant(VARIANT Var, std::vector<T>& Vec)
{
    CComSafeArray<T> SafeArray;
    SafeArray.Attach(Var.parray);
    ULONG Count = SafeArray.GetCount();
    Vec.resize(Count);
    for(ULONG Index = 0; Index < Count; Index++)
    {
        Vec[Index] = SafeArray[Index];
    }
}
....
std::vector<double> Vec;
VARIANT Var = ...;
FromVariant(Var, Vec);
...

当然,如果数组包含非POD类型,事情就会变得很麻烦(关于内存/生命周期管理),但是它仍然是可行的.

Of course things get hairy (in regards to memory / lifetime management) if the array contains non-POD types, but it is still doable.

这篇关于在C ++中转换为/从VARIANT类型转换的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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