“WebAssembly manages memory as a single contiguous, mutable byte array called Linear Memory. Allocated in fixed 64KB pages, Linear Memory is represented in JavaScript as a standard WebAssembly.Memory object wrapping an ArrayBuffer, allowing zero-copy sharing between JS and Wasm.”
Managing 64KB memory pages, raw byte manipulation, and sharing memory with JavaScript TypedArrays.
(module
(memory (export "memory") 1) ;; 1 page = 64 KiB
;; Store integer at memory offset
(func $write (param $offset i32) (param $val i32)
local.get $offset
local.get $val
i32.store)
(export "write" (func $write))
)const memory = new WebAssembly.Memory({ initial: 1 });
const { instance } = await WebAssembly.instantiate(wasmBytes, { env: { memory } });
instance.exports.write(0, 42); // Store 42 at byte index 0
const view = new Int32Array(memory.buffer);
console.log('Read from JS buffer:', view[0]); // 42Declare memory module: (memory (export "mem") 1) (1 page = 64KB = 65,536 bytes)
Store bytes from Wasm using i32.store, i32.store8, or f64.store at byte offset
JavaScript creates a TypedArray view: new Uint8Array(memory.buffer)
Both JavaScript and Wasm read/write identical memory addresses without copying
Memory dynamically expands on demand using memory.grow(additionalPages)
Zero-copy ArrayBuffer memory sharing allows passing 4K video frames or multi-megabyte image buffers to Wasm with 0ms transfer latency.