How to convert Array of bytes to Variant

跟風遠走 提交于 2019-12-04 04:14:39

问题


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


回答1:


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]));


来源:https://stackoverflow.com/questions/13143372/how-to-convert-array-of-bytes-to-variant

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!