🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly Linear Memory

Linear memory is one flat array of bytes that a module can read and write. JavaScript sees the same bytes through a typed array view.

Export one page of memory

This module exports its memory and two helpers. Store writes one byte. Load reads one byte.

(module
  (memory (export "memory") 1)
  (func (export "store") (param i32 i32)
    local.get 0
    local.get 1
    i32.store8)
  (func (export "load") (param i32) (result i32)
    local.get 0
    i32.load8_u))

Write bytes from JavaScript

Make a Uint8Array view over the memory. Then write 65 and 66 into the first two bytes.

const memory = instance.exports.memory;
const view = new Uint8Array(memory.buffer);
view[0] = 65;
view[1] = 66;
console.log(view[0]);
console.log(view[1]);

Store from Wasm, read from JavaScript

The Wasm store writes 65 at address 0. The view then reads 65 at the same address.

instance.exports.store(0, 65);
const view = new Uint8Array(instance.exports.memory.buffer);
console.log(view[0]);
console.log(instance.exports.load(0));

Example

(async () => {
  const B64 = "AGFzbQEAAAABCwJgAn9/AGABfwF/AwMCAAEFAwEAAQcZAwZtZW1vcnkCAAVzdG9yZQAABGxvYWQAAQoTAgkAIAAgAToAAAsHACAALQAACw==";
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes);
  const view = new Uint8Array(instance.exports.memory.buffer);
  instance.exports.store(0, 65);
  instance.exports.store(1, 66);
  console.log(view[0]);
  console.log(view[1]);
  console.log(instance.exports.load(0));
})();

Key points

  • Linear memory is one flat array of bytes.
  • A page is one block of memory with 65536 bytes.
  • A module starts with a set number of pages.
  • JavaScript reads the bytes through a Uint8Array view.
  • A store from Wasm and a write from JavaScript touch the same bytes.

In this example, the bytes are decoded and started into an instance. Then a view is made over the exported memory. The Wasm store writes 65 at address 0 and 66 at address 1. The view reads 65 and 66. And the Wasm load reads 65 back from address 0.

Note

An address past the end of memory traps.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

How many bytes does one WebAssembly memory page hold?