在 C++ 中与 VARIANT 类型相互转换的简单方法;
是否有任何易于使用、高级类或库可让您与 Visual C++ 中的 VARIANT
交互?
更具体地说,我想在 POD 类型(例如 double
、long
)、字符串(例如 CString
)和容器(例如std::vector
) 和 VARIANT
。例如:
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 的人们总是这样做,因此很可能有一个单个方便的库来处理各种转换。但我所能找到的只是各种各样的包装类,每个类都转换几种类型:
- _variant_t 或 CComVariant 适用于 POD 类型
- _bstr_t 、CComBSTR 或 BSTR 用于字符串
- CComSafeArray 或 SAFEARRAY 用于数组
除了切换到 Visual Basic 之外,是否有任何简单的方法可以避免这种尴尬的内存管理和按位 VT_ARRAY | 的噩梦? VT_I4 代码?
相关问题:
Are there any easy-to-use, high-level classes or libraries that let you interact with VARIANT
s in Visual C++?
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 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?) 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
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?
Related questions:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,大部分艰苦的工作已经通过各种包装类为您完成了。我更喜欢 _variant_t 和 _bstr_t,因为它们更适合与 POD 类型和字符串之间的转换。对于简单数组,您真正需要的只是模板转换函数。如下所示:
当然,如果数组包含非 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:
Of course things get hairy (in regards to memory / lifetime management) if the array contains non-POD types, but it is still doable.