VariantArrayLockUnlock (C++)
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
float CalculateMean(Variant array)
{
int len;
float lsum;
Variant *pElem;
int i;
lsum = 0;
/* Lock the array and obtain the pointer to the memory that holds the actual values. */
pElem = (Variant*)VarArrayLock(array);
/* Obtain the length of the array. */
len = VarArrayHighBound(array, 1) - VarArrayLowBound(array, 1) + 1;
/* Iterate over the elements of the array and calculate the sum. */
for (i = 0; i < len; i++)
lsum += (float)pElem[i];
/* Unlock the array. */
VarArrayUnlock(array);
/* Calculate the mean. */
return(lsum / len);
}
int _tmain(int argc, _TCHAR* argv[])
{
double x;
int l = 0;
Variant* arr = NULL;
Variant array;
/* Loop until one issues the stop condition (X = 0). */
while (true)
{
/* Read a new element from the console. */
printf("Enter a double value (0 for stop): ");
scanf("%lf", &x);
/* The stop condition */
if (x == 0)
break;
l++;
arr = (Variant*)realloc(arr, l * sizeof(Variant));
/* Add an element to the Variant array. */
arr[l - 1] = x;
}
/* Create a variant array that has variant elements. */
if (l == 0)
{
return -1;
}
array = VarArrayOf(arr, l - 1);
/* Write the "mean" results to the console. */
printf("Mean of the given values is: %lf\n", CalculateMean(array));
return 0;
}
Uses
- System.Variants.VarArrayOf ( fr | de | ja )
- System.Variants.VarArrayLock ( fr | de | ja )
- System.Variants.VarArrayUnlock ( fr | de | ja )