Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variant arrays in Delphi

Tags:

I have two Delphi7 programs: a COM automation server (EXE) and the other program which is using the automation server.

I need to pass an array of bytes from one program to the other.

After some searching I've found that using variant arrays is the way to go (correct me please if you know any better methods).

My question is: How do I create a variant array in one program, and then how do I read its values in the other?

I know about VarArrayCreate and VarArrayLowBound/VarArrayHighBound, but I'm unsure on how to do this properly.

Thanks!

like image 620
Steve Avatar asked Sep 01 '10 15:09

Steve


People also ask

What is a variant in Delphi?

Description. The Variant type is a dynamic type. A Variant variable can change type at runtime, sometimes storing an integer, other times a string, and other times an array. Delphi automatically casts numbers, strings, interfaces, and other types to and from Variant s as needed.

What is a variant array?

A variant array is set up so you can store anything in the individual elements (intersect of row and column). In the code you show they are creating a two dimensional array, but there is only a single column and the same number of rows as found in the listobject DataBodyRange.


2 Answers

You create it like that:

Declarations first

var
  VarArray: Variant;
  Value: Variant;

Then the creation:

VarArray := VarArrayCreate([0, Length - 1], varVariant);

or you could also have

VarArray := VarArrayCreate([0, Length - 1], varInteger);

Depends on the type of the data. Then you iterate like this:

i := VarArrayLowBound(VarArray, 1);
HighBound := VarArrayHighBound(VarArray, 1);

while i <= HighBound do
begin
  Value := VarArray[i];
  ... do something ...
  Inc(i);
end;

Finally you clear the array when you don't need it anymore. EDIT: (This is optional, see In Delphi 2009 do I need to free variant arrays? )

VarClear(VarArray);

That is all there is to it. For another example look at the official Embracadero Help

EDIT:

The array should be created only once. Then just use it like shown in the above example.

like image 128
Runner Avatar answered Sep 19 '22 09:09

Runner


For the other side:

(assuming Value is the Variant parameter and the element type is WideString)

var
  Source: PWideStringArray;

if VarIsArray(Value) then begin
  Source:= VarArrayLock(Value);
  try
    for i:= 0 to TVarData(Value).VArray^.Bounds[0].ElementCount - 1 do
      DoWhatEverYouWantWith(Source^[i]);
    end;
  finally
    VarArrayUnlock(Value);
  end;
end;  
like image 30
Uwe Raabe Avatar answered Sep 21 '22 09:09

Uwe Raabe