How can I get the adress of a static mut from wasm (rust) to js?

389 views Asked by At

I have a rust-wasm project where I need to fill a buffer in webassembly before passing it to my js script and then display it with a canvas.

(Inspired by this article)

static mut BUFFER: [u32; WIDTH * HEIGHT] = [0; WIDTH * HEIGHT];

But a static mut in rust is unsafe, so I can’t declare it with #[wasm_bindgen]

How can I get the address of this static buffer in my js script?

EDIT :

I have seen this solution:

const { instance } = await WebAssembly.instantiateStreaming(
          fetch("./demo.wasm")
        );

const buffer_address = instance.exports.BUFFER.value;

I don’t really understand what is happening in this code, and I can’t use that because I use the wasm-pack buildtool: it creates for me the .js file corresponding to the wasm file, and I still can’t get the Buffer address.

Any help would be appreciated

1

There are 1 answers

0
Zhi An Ng On

Your linked article uses #[no_mangle], which makes BUFFER exported.

#[no_mangle]
static mut BUFFER: [u32; WIDTH * HEIGHT] = [0; WIDTH * HEIGHT];

The exported BUFFER can then be found on the instance, via instance.exports.BUFFER.value;.