An easy way to convert to / from VARIANT types in C ++

Are there easy-to-use classes or high-level libraries that allow you to interact with VARIANT in Visual C ++?

In particular, I would like to convert POD types (e.g. double , long ), strings (e.g. CString ) and containers (e.g. std::vector ) and VARIANT s. 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> 

I (naively?) Suggested that people working with COM do this all the time, so most likely there will be the only convenient library that handles all kinds of conversions. But all I could find was a motley assortment of wrapper classes, each of which converts several types:

Is there a simple way โ€” not before switching to Visual Basic โ€” to avoid this nightmare of inconvenient memory management and bitwise code VT_ARRAY | VT_I4 VT_ARRAY | VT_I4 ?

Related questions:

  • CComVariant vs. _variant_t, CComBSTR vs. _bstr_t
  • Convert VARIANT to ...?
  • What is the best way to convert VARIANT_BOOL to a C ++ bool?
+6
windows visual-c ++ variant
source share
1 answer

Well, most of the hard work has already been done for you with various wrapper classes. I prefer _variant_t and _bstr_t, as they are more suitable for converting to / from POD types and strings. For simple arrays, you really need a 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); ... 

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

+4
source share

All Articles