Custom Variant Wrapper for TDataset - Part 3

In Part 2 I explained how to initialize a custom variant’s data structure and how to create a TCustomVariantType descendant to implement the methods required to make the variant useful.  Now I will start to explain which methods need to be implemented, what they do and how they do it.  In this part we will discuss clearing your variant and copying your variant to another variant.

Since we had to create a function to initialize our variant’s data structure, in effect creating it, it stands to reason that we will need a method to uninitialize, or destroy it.  This method is TCustomVariantType.Clear.  Clear takes a single argument which is the variant to be cleared.  The Clear method is called whenever the variant needs to be re-initialized and also when the variant goes out of scope and needs to be destroyed.  This is where you will free any memory buffers or objects that were created for the variant instance and where you will reset the variant to an ‘empty’ state.  If your custom variant doesn’t need to free any memory and doesn’t require any special clear processing you can simply call TCustomVariantType.SimplisticClear.  This will set the variant’s type to varEmpty and set the remainder of the variant’s data structure to zeroes.  Like this:


procedure TDatasetVariant.Clear(var V: TVarData);
begin
SimplisticClear(V);
end;

Or you can choose to do the work yourself.  Like this:


procedure TDatasetVariant.Clear(var V: TVarData);
begin
TDatasetData(v).VType := varEmpty;
TDatasetData(V).VDataset := 0;
end;

Another thing that you need to be able to handle is copying the custom variant to another variant of the same type.  This happens when the user assigns ( := ) one of your custom variants to another variant.  The method that does this is TCustomVariantType.Copy.  Copy takes three arguments; Dest which the destination variant of the copy operation, Source which is the source variant of the copy operation and IndirectIndirect has something to do with whether or not the variant owns its data or just points to it.  This seems to be controlled by setting a certain bit in the variant’s type.  Since there is no way to set this bit when using TCustomVariantType, this argument would seem to be irrelevant to us.

Copying a variant can be as simple as copying the entire variant data structure to the destination unchanged or it may involve allocating a new buffer or object and copying the buffer’s or object’s contents.  If all you need to do is copy the variant data structure you can use TCustomVariantType.SimplisticCopy to do the job.  Otherwise, you will have to write the code yourself.  For the TDataset variant we just need to copy the variant data structure, so our Copy method looks like this:


procedure TDatasetVariant.Copy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean);
begin
SimplisticCopy(Dest, Source, Indirect);
end;

Leave a Reply