How to Use Shared Memory Between Rust WASM and JavaScript

Web
Rust WASM and JavaScript share memory via the linear buffer, allowing direct read/write access without data copying.

Shared memory between Rust WASM and JavaScript is handled automatically via the WebAssembly linear memory buffer, which both environments access directly. You allocate memory in Rust using Vec or Box, export the data pointer and length to JavaScript, and read/write the buffer in JS using Uint8Array.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn get_data_ptr() -> u32 {
    let data: Vec<u8> = vec![1, 2, 3, 4];
    let ptr = data.as_ptr() as u32;
    std::mem::forget(data); // Prevent deallocation so JS can read the memory
    ptr
}

#[wasm_bindgen]
pub fn get_data_len() -> u32 {
    4
}
import { get_data } from './pkg';
const ptr = get_data_ptr();
const len = get_data_len();
const memory = wasmInstance.exports.memory;
const buffer = new Uint8Array(memory.buffer, ptr, len);
console.log(buffer); // [1, 2, 3, 4]