1

I'm trying to convert a variant array (of doubles, but it could be anything I guess) to a dynamic array. I usually use the DynArrayFromVariant and DynArrayToVariant procedures, but in this case my variant arrays are 1 based. These two functions only seem to work on 0 based arrays. Any idea how I could do what I need to do?

1
  • 1
    Call SetLength to allocate the dynamic array and then populate it with a for loop Commented Jul 3, 2012 at 11:05

1 Answer 1

8

If you know the type of your array elements you can write more efficient (while less generic) code:

function DoubleDynArrayFromVarArray(const V: Variant): TDoubleDynArray;
var
  P: Pointer;
  Count: Integer;
begin
  Result := nil;
  if not VarIsArray(V) or (VarType(V) and varTypeMask <> varDouble) or
    (VarArrayDimCount(V) <> 1) then
    raise EVariantInvalidArgError.Create(SVarInvalid);

  Count := VarArrayHighBound(V, 1) - VarArrayLowBound(V, 1) + 1;
  if Count = 0 then
    Exit;

  P := VarArrayLock(V);
  try
    SetLength(Result, Count);
    Move(P^, Result[0], Count * SizeOf(Double));
  finally
    VarArrayUnlock(V);
  end;
end;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.