How to convert Array of bytes to Variant

delphi, variant

Solution

According to the comment trail, you need to create a `SAFEARRAY` of bytes. Which is done like this in Delphi:

V := VarArrayCreate([0, N-1], varByte);

Or, if the `SAFEARRAY` needs 1-based indexing:

V := VarArrayCreate([1, N], varByte);

You can then populate the array in a loop using `V[i] := ...`.

If you have a Delphi dynamic `array of Byte`, and the expected `SAFEARRAY` uses 0-based indexing, then you can simply write:

V := a;

If you have a lot of data to transfer then the element by element poking of the data that the RTL offers is pretty much hopeless. Even the simple `v := a` approach results in element by element copying which will be horribly slow for large amounts of data.

In your position, I'd blit the array in one go. Like this:

var
  i: Integer;
  a: array of Byte;
  V: Variant;
  SafeArray: PVarArray;
....
// populate a
V := VarArrayCreate([0,high(a)], varByte);
SafeArray := VarArrayAsPSafeArray(V);
Move(Pointer(a)^, SafeArray.Data^, Length(a)*SizeOf(a[0]));

Or, if you need to use 1-based indexing:

V := VarArrayCreate([1,Length(a)], varByte);
SafeArray := VarArrayAsPSafeArray(V);
Move(Pointer(a)^, SafeArray.Data^, Length(a)*SizeOf(a[0]));

Problem

How to convert a byte array to Variant? I have a WebService that should receive an array of byte, but it only accepts variable of type VARIANT, I wonder how to convert in order to pass it as parameter for Web Services. thank you

Original source

Related problems