The variant type is often used to pass parameters to com objects or receive values returned from COM objects. You can also write methods that return the variant type by yourself. The input parameters (for example, in an automated operation, dependency on the method you call) of the possible (and often) Type of dependency returned by the function. Idispatch: invoke may return a result that contains the variant type, such as byte, word, float, double, date, and BSTR, (For details, see the definition of the variant structure on msdn ). In the following example, assume that the type is a variant of BSTR, that is, the value in the string is referenced through bsrtval, and its advantage is that in ANSI applications, there is a constructor that converts the value referenced by lpcwchar to a cstring (see section BSTR-to-cstring ). In Unicode mode, it will become a standard cstring constructor. For more information, see warn about the default: widechartomultibyte conversion and whether you think it is acceptable (in most cases, you will be satisfied ). Variant vadata;
Vadata = m_com.yourmethodhere ();
Assert (vadata. Vt = vt_bstr );
Cstring strdata (vadata. bstrval );
You can also create more common conversion routines based on different VT domains. For this reason, you may consider:
Cstring varianttostring (variant * VA)
{
Cstring S;
Switch (va-> VT)
{/* Vt */
Case vt_bstr:
Return cstring (vadata-> bstrval );
Case vt_bstr | vt_byref:
Return cstring (* vadata-> pbstrval );
Case vt_i4:
S. Format (_ T ("% d"), va-> lval );
Return S;
Case vt_i4 | vt_byref:
S. Format (_ T ("% d"), * va-> plval );
Case vt_r8:
S. Format (_ T ("% F"), va-> dblval );
Return S;
... The remaining type conversion is done by the reader.
Default:
Assert (false); // unknown variant type (this assert is optional)
Return cstring ("");
}/* Vt */
}