I have a demo fiddle online at https://webassembly.studio/?f=0r9gxzb9rdq where I'm using an array buffer that gets shared between JS and WebAssembly.
As suggested in this answer How to access WebAssembly linear memory from C/C++, I'm declaring it as a global array that I'm reading and writing to, along with a helper function to return the starting address:
const SIZE = 6 * 1000 * 1000;
int array[SIZE]
WASM_EXPORT
int* getStartByteOffset() {
return &array[0];
}
Then, in JS-land, once I load the wasm file and get the module instance:
const SIZE = 6 * canvas.width * canvas.height;
const heap = instance.exports.memory.buffer;
const offset = instance.exports.getStartByteOffset()
const arrayView = new Int32Array(heap, offset, SIZE)
This works, and now JS and WebAssembly can access this array. But it's not the way I want to do it. I don't know the required array size beforehand (the canvas could turn out to be any size), so I'm idiotically preallocating one large enough to accommodate 1000x1000 pixels (where each pixel needs six 32-bit wide ints).
What I want to do is calculate in JS the memory required, and pass it in as a WebAssembly.Memory once I know how many 64k pages I need:
fetch('../out/main.wasm').then(response => response.arrayBuffer())
.then((bytes) => {
WebAssembly.instantiate(bytes, {
env: {
memoryBase: 0,
memory: new WebAssembly.Memory({
initial: 1 + ((6 * 4 * canvas.width * canvas.height) >> 16)
})
}
}).then((wasm) => {...});
});
What I can't figure out is the precise way to access the WebAssembly.Memory buffer using C. The Internet is crammed full of code samples on how the JS side of the API works, but all the code samples I can ever find on the WebAssembly side are written in WAT.