rezoner
rezoner

Reputation: 1967

How to pass custom Memory object to WebAssembly?

Why is my custom memory object being ignored?

let memory = new WebAssembly.Memory({ initial: 16, maximum: 16, shared: true });

console.log(memory.buffer); 

// logs: SharedArrayBuffer(1048576) as expected

WebAssembly.instantiateStreaming(fetch('../out/main.wasm'), {
  
  env: { memory }

}).then(results => {
    
  console.log(results.instance.exports.memory.buffer);

    // logs: ArrayBuffer(131072) - both size and shared parameter is being ignored
  
});

Here is a fiddle https://webassembly.studio/?f=t4fgszgzy9

background: I have some big (64MB) Uint32Array and I want to delegate some processing to C/C++ without copying the whole array every time since the overhead of copying data in a loop would defeat the purpose of this optimization.

Why do I want SharedArrayBuffer? I am also using this data in WebWorkers and I find it more elegant than transfering objects.

Upvotes: 2

Views: 722

Answers (1)

sbc100
sbc100

Reputation: 3022

Presumably you have built a wasm module that exports its memory rather than importing? In this case the memory in the env you are passing will be ignored.

You can see with wasm-objdump if this is the case.

What tools are you using to build your module. If you are linking with wasm-ld you can pass --import-memory to the linker if you want memory to be imported.

Upvotes: 2

Related Questions