Inside the excellent WasmFiddle tool, I'm using this WASM function:
int f(char *in, char *out, int len) {
for (int i = 0; i < len; i++) {
out[4*i] = in[i];
out[4*i+1] = in[i];
out[4*i+2] = in[i];
out[4*i+3] = 255;
}
return 0;
}
and this JS code:
var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);
var width = 1000, height = 1000;
var array = new Uint8Array(width*height).fill().map(() => Math.round(Math.random() * 255)); // random values
var rgba = new Uint8ClampedArray(4*width*height);
wasmInstance.exports.f(array, rgba, width*height);
The last line is an error because it fails to pass the reference/pointer of array
and rgba
.
How to do this, in particular in this WasmFiddle environment?
I've read Pass array to C function with emscripten, How to handle passing/returning array pointers to emscripten compiled code?, Pass a JavaScript array as argument to a WebAssembly function but I don't see how to apply this here.
Attempt #1 inspired from Passing arrays between wasm and JavaScript:
var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);
var width = 10, height = 10;
var array = new Uint8Array(wasmInstance.exports.memory.buffer, 0, width*height).fill().map(() => Math.round(Math.random() * 255)); // random values
var rgba = new Uint8ClampedArray(wasmInstance.exports.memory.buffer, width*height, 4*width*height);
wasmInstance.exports.f(array.byteOffset, rgba.byteOffset, width*height);
log(array);
log(rgba);
but in the result we see [0, 0, 0, 255, 0, 0, 0, 255, ...]
: other values haven't been modified as expected. Also when increasing the size to width and height = 1000, it doesn't work anymore.