Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Array of bytes to Variant

Tags:

delphi

variant

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

like image 682
Jose Eduardo Avatar asked Nov 21 '25 01:11

Jose Eduardo


1 Answers

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]));
like image 159
David Heffernan Avatar answered Nov 23 '25 16:11

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!