Member-only story
How To Pass Arrays Between JavaScript and WASM in Rust
Exploring this friendly interface
Due to WASM’s memory model, passing arrays (and nested arrays) might be quite challenging if you’re trying to do things securely since wasm memory stores its values as array buffers of scalar types.
However, we luckily have the wasm-bindgen
(and js-sys
) crates that provide a friendly interface to work on when exchanging data between Javascript and WebAssembly.
I should also mention that whenever you are working with WebAssembly, you should always avoid exchanging data between JS and your WASM binary if you are developing with performance as one of your goals.
Generally, we want WASM to work with heavy computations, query, and data in its linear memory and only return small amounts of data due to the computations.
Wasm functions take and return scalar values as an ArrayBuffer
. Luckily wasm-bindgen
helps with a lot of stuff, but it doesn’t do everything.
Let’s look at how you can pass (or return) arrays using the type.
Setup
Since we are working with WebAssembly, more specifically, that targets a web build (it’s meant to work along with js), the best setup we can get is by using wasm-bindgen
with its procedural macros.