Problem with CopyToNativeArray in WebAssembly

Elements 11.0.0.2675

Hi,

It seems that there is a problem with the aTypedArrayOffset argument of the CopyToNativeArray method. If the offset is anything other than zero then the number of copied items is less than aSize (how much less depends on the offset). A test case:

begin
  var buf := WebAssembly.Eval('new Uint8Array([1, 2, 3, 4, 5])') as dynamic;

  var arr1 := new Byte[5]; 
  EcmaScriptObject(buf).CopyToNativeArray(0, arr1, 0, 5); //OK, arr1 is [1, 2, 3, 4, 5]

  var arr2 := new Byte[4]; 
  EcmaScriptObject(buf).CopyToNativeArray(0, arr2, 1, 4); //WRONG, arr2 is [2, 3, 0, 0]
end;

I think, from looking at the code, the idea is that aSize is the size of the array, not the number of bytes you want to be copied:

So if you have an array sized 10, and you copy from offset 3, there are only seven items to copy.

    method CopyToNativeArray<T>(aNativeOffset: Integer; aNativeArray: array of T; aTypedArrayOffset, aSize: Integer);
    begin
      aSize := Math.Min(aSize, (aSize - aNativeOffset));
      WebAssemblyCalls.CopyFromArray(^Byte(@aNativeArray[aNativeOffset]), Handle, aTypedArrayOffset, aSize * sizeOf(T));
    end;

I don’t get it. Do you mean that aSize is supposed to be the size of the source array buf (it is the size of the destination array in the above example)? Even if so and I do CopyToNativeArray(0, arr2, 1, 5) then the number of copied elements is 3. To get the correct result I need to do CopyToNativeArray(0, arr2, 1, 6) and 6 doesn’t correspond to anything. Moverover, if I do this CopyToNativeArray(0, arr2, 2, 5); only one element gets copied. Also, if aSize is the size of the array and not the number of elements to copy then how am I supposed to copy just the number of elements I need?

I’m just guessing, but yes. I didn’t write this API, nor did I ever use it; I’ll have to defer to my colleague, later.

I suppose you wouldn’t, with this API.

Marc, note that if I change aSize along with aTypedArrayOffset then I acually can copy the number of elements I need so it doesn’t really seem that aSize was thought as the source array size. Also, when aTypedArrayOffset is zero then aSize is the number of elements to copy. The problem is that the value I need to pass as aSize when aTypedArrayOffset is not zero doesn’t really correspond to anything that it should.

Update: the formula is

aSize = 2 * aTypedArrayOffset + number of elements to copy

for an Uint8Array.

Hi, there was an issue in CopyToNativeArray (javascript side). It has been fixed in today’s build.

Great! Thank you Diego. I’ll check it on monday then.

1 Like