VariantArrayLockUnlock (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example shows how to use the VarArrayOf, VarArrayLock, and VarArrayUnlock functions from the Variants unit. You need to use a pointer to hold the memory addresses to the values from the array you create. This example calculates the mean of some values that are read and stored in a Variant array.

Code

function CalculateMean(const LArray: Variant): Double;
var
  LLen: Integer;
  LSum: Double;
  PElem: PVariant;
  I: Integer;

begin
  LSum := 0;

  { Lock the array and obtain the pointer to the memory that holds the actual values. }
  PElem := VarArrayLock(LArray);

  { Obtain the length of the array }
  LLen := VarArrayHighBound(LArray, 1) - VarArrayLowBound(LArray, 1) + 1;

  { Iterate over the elements of the array and calculate the sum. }
  for I := 0 to LLen - 1 do
  begin
    { PElem^ holds the next Variant element in the array. }
    LSum := LSum + PElem^;
    Inc(PElem);
  end;

  { Unlock the array. }
  VarArrayUnlock(LArray);

  { Calculate the mean. }
  Result := LSum / LLen;
end;

var
  X: Double;
  L: Integer;
  LValues: array of Variant;
  LVarArray: Variant;

begin
  { Loop until one issues the stop condition (X = 0). }
  while True do
  begin
    { Read a new element from the console. }
    Write('Enter a double value (0 for stop): '); Readln(X);

    { The stop condition }
    if X = 0 then
      Break;

    { Compute the length of an array of variants. }
    L := Length(LValues);
    { Set the new length of the variant array. }
    SetLength(LValues, L + 1);
    { Add an element to the Variant array. }
    LValues[L] := X;
  end;

  { Create a variant array that has variant elements. }
  LVarArray := VarArrayOf(LValues);
  { Write the 'mean' results to the console. }
  Writeln('Mean of the given values is: ', CalculateMean(LVarArray));
end.

Uses