In Ole, ActiveX, and COM, the variant data type provides a very effective mechanism because it includes both the data itself and the data type, therefore, it can realize various automatic data transmission. Let's take a look at a simplified version defined by variant in The IDL. h file:
Struct tagvariant {
Vartype VT;
Union {
Short ival; // vt_i2.
Long lval; // vt_i4.
Float fltval; // vt_r4.
Double dblval; // vt_r8.
Date; // vt_date.
BSTR bstrval; // vt_bstr.
...
Short * pival; // vt_byref | vt_i2.
Long * plval; // vt_byref | vt_i4.
Float * pfltval; // vt_byref | vt_r4.
Double * pdblval; // vt_byref | vt_r8.
Date * pdate; // vt_byref | vt_date.
BSTR * pbstrval; // vt_byref | vt_bstr.
};
};
Obviously, the variant type is a C structure, which contains a type member VT, some reserved bytes, and a large union type. For example, if VT is vt_i2, we can read the value of variant from ival. Similarly, when assigning values to a variant variable, you must specify its type first. For example:
Variant Va;
: Variantinit (& VA); // Initialization
Int A = 2002;
Va. Vt = vt_i4; // specifies the long data type.
Va. lval = A; // value assignment
To facilitate variable processing of the variant type, windows also provides such useful functions:
Variantinit -- initialize the variable to vt_empty;
Variantclear -- remove and initialize variant;
Variantchangetype -- change the variant type;
Variantcopy -- releases the memory connected to the target variant and copies the source variant.
The colevariant class encapsulates the variant structure. Its constructor has very powerful functions. When constructing an object, it first calls variantinit for initialization, then calls the corresponding constructor according to the standard type in the parameter, and uses variantcopy for conversion and value assignment, when a variant object is out of the valid range, its destructor is automatically called. Because the Destructor calls variantclear, the corresponding memory is automatically cleared. In addition, colevariant's value assignment operator provides great convenience for us in the conversion from variant type. For example, the following code:
Colevariant V1 ("this is a test"); // directly construct
Colevariant v2 = "this is a test ";
// The result is of the vt_bstr type and the value is "this is a test"
Colevariant V3 (long) 2002 );
Colevariant V4 = (long) 2002;
// The result is of the vt_i4 type and the value is 2002.
_ Variant_t is a variant class used for com. Its functions are similar to those of colevariant. However, when using the Visual C ++. Net MFC application, you must add the following two sentences before the code file:
# I nclude "comutil. H"
# Pragma comment (Lib, "comsupp. lib ")