Skip to content

[WASM] How to read from SharedArrayBuffer? #46016

@ivan-prodanov

Description

@ivan-prodanov

Context: My react app is accessing a large dataset from a worker using a SharedArrayBuffer. I'd like to process the SharedArrayBuffer in C# with minimal overhead. I have a hard time converting the SharedArrayBuffer to a Span in C#.
Here's what I tried:

public static int TestSum(SharedArrayBuffer sharedArrayBuffer)
{
    Int32Array array = new Int32Array(sharedArrayBuffer);
    Span<int> nativeArray = array; // error                        
    
    int sum = 0;
    for (int i = 0; i < nativeArray.Length; i++)
    {
        sum += nativeArray[i];
    }

    return sum;
}

This unfortunately fails with "Object '...' is not a typed array" in js_typed_array_to_array.

Here's the function from dotnet.js:

js_typed_array_to_array : function (js_obj) {
	if (!!(js_obj.buffer instanceof ArrayBuffer && js_obj.BYTES_PER_ELEMENT)) 
	{
		var arrayType = js_obj[Symbol.for("wasm type")];
		var heapBytes = this.js_typedarray_to_heap(js_obj);
		var bufferArray = this.mono_typed_array_new(heapBytes.byteOffset, js_obj.length, js_obj.BYTES_PER_ELEMENT, arrayType);
		Module._free(heapBytes.byteOffset);
		return bufferArray;
	}
	else {
		throw new Error("Object '" + js_obj + "' is not a typed array");
	} 

I was able to workaround this by changing

if (!!(js_obj.buffer instanceof ArrayBuffer && js_obj.BYTES_PER_ELEMENT)) 

to

if (!!(js_obj.buffer instanceof (ArrayBuffer, SharedArrayBuffer) && js_obj.BYTES_PER_ELEMENT)) 

Now the code executes with no errors, however there's a copying operation being done in mono_typed_array_new. Doesn't that make the whole idea behind using a SharedArrayBuffer in order to avoid copying useless?

Is this the proper way to process a SharedArrayBuffer? Is there a way to process it without copying the data?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions