Storing the Data of a Custom Variant Type

From RAD Studio
Jump to: navigation, search

Go Up to Defining Custom Variants Index


Variants store their data in the TVarData record type. This type is a record that contains 16 bytes. The first word indicates the type of the variant, and the remaining 14 bytes are available to store the data. While your new Variant type can work directly with a TVarData record, it is usually easier to define a record type whose members have names that are meaningful for your new type, and cast that new type onto the TVarData record type.

For example, the VarConv unit defines a custom variant type that represents a measurement. The data for this type includes the units (TConvType) of measurement, as well as the value (a double). The VarConv unit defines its own type to represent such a value.

Delphi:

 TConvertVarData = packed record
   VType: TVarType;
   VConvType: TConvType;
   Reserved1, Reserved2: Word;
   VValue: Double;
 end;

This type is exactly the same size as the TVarData record. When working with a custom variant of the new type, the variant (or its TVarData record) can be cast to TConvertVarData, and the custom Variant type simply works with the TVarData record as if it were a TConvertVarData type.

Note: When defining a record that maps onto the TVarData record in this way, be sure to define it as a packed record.

If your new custom Variant type needs more than 14 bytes to store its data, you can define a new record type that includes a pointer or object instance. For example, the VarCmplx unit uses an instance of the class TComplexData to represent the data in a complex-valued variant. It therefore defines a record type the same size as TVarData that includes a reference to a TComplexData object.

Delphi:

 TComplexVarData = packed record
   VType: TVarType;
   Reserved1, Reserved2, Reserved3: Word;
   VComplex: TComplexData;
   Reserved4: LongInt;
 end;

Object references are actually pointers (two Words), so this type is the same size as the TVarData record. As before, a complex custom variant (or its TVarData record), can be cast to TComplexVarData, and the custom variant type works with the TVarData record as if it were a TComplexVarData type.

See Also