سؤال

I access with my program a COM object (in my example CANoe) and call a method get_Value to get the value of a variable in the COM object. The pointer pVariable is a pointer to the COM object of the variable:

 VARIANT variable; 
 result = pVariable->get_Value(&variable);

To work with the value in c++ I want to save the value in the VARIANT variable in an integer variable. How can I cast the value in the VARIANT variable to an integer variable?

هل كانت مفيدة؟

المحلول

There are a lot of variant access macros in OleAuto.h. When you have get the value, you should ensure that it has the correct type. Then you can read it:

int value;

if (V_VT(variable) == VT_INT)
{
    value = V_INT(variable);
}

There are several integer types defined for variants. Please look at wtypes.h and check what actual type is stored in your current variant object and use the appropriate V_xxx macro.

نصائح أخرى

Just access the variant value after you made sure you got a proper integer value. Like this:

 VARIANT variable; 
 HRESULT hr = pVariable->get_Value(&variable);
 if (SUCCEEDED(hr)) hr = VariantChangeType(&variable, &variable, 0, VT_I4);
 if (SUCCEEDED(hr)) this->Yadayada = variable.lVal;
 else ReportFailure(hr);

It depends what variant type you are talking about. For example, a variant holding a date value will likely fail if you try to convert to an integer.

HRESULT hr = VariantChangeType (&VariantDest, &VariantSource, 0, VT_I4);
long t = VariantSource.lVal;

Don't forget to check the HRESULT value.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top