conversion between std::vector and _variant_t

社会主义新天地 提交于 2019-12-08 05:02:48

问题


I need to convert between std::vector and _variant_t to avoid looping when writing/sending data into some file (database, Excel, etc.)

Could you please let me know how to proceed with that?

I was trying to get a std::vector<_variant_t> and somehow put into another _variant_t variable, but direct conversion is not supported and even if it's done there's no either method or some kind of wrapper to get this vector into a _variant_t variable.

I would prefer not to deal with any loops.


回答1:


A std::vector and _variant_t are incompatible types. The _variant_t type is designed to support scenarios where a COM interface needs to support multiple types of values for the same parameters. It's set of values is limited to those for which COM understands how to marshal. std::vectory is not one of those types.

The standard way to store a collection of values into a _variant_t is to do so as a safe array. So the easiest solution is to convert the std::vector to a safe array and store that in the variant. There's really no way to avoid a loop here

// Convert to a safe array
CComSafeArary<INT> safeArray;
std::vector<int> col = ...;
for (std::vector<int>::const_iteator it = col.begin(); it != col.end(); it++) {
  safeArray.Add(*it);
}

// Initialize the variant
VARIANT vt;
VariantInit(&vt);
vt.vt = VT_ARRAY | VT_INT;
vt.parray = safeArray.Detach();

// Create the _variant_t
_variant_t variant;
variant.Attach(vt);


来源:https://stackoverflow.com/questions/7261258/conversion-between-stdvector-and-variant-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!