Sikau

WebAssembly · Day 7 · about 35 min

Linear memory

Share strings with wasm through its memory: write bytes, call, read back.

Wasm only understands numbers

Wasm functions take and return numbers. To pass a string or an array you write its bytes into the module's linear memory — one big ArrayBuffer — and pass a pointer and a length. This JavaScript "glue" is what tools like wasm-bindgen generate for you.

The glue

function writeString(memory, ptr, text) {
  const bytes = new TextEncoder().encode(text);
  new Uint8Array(memory.buffer).set(bytes, ptr); // a view over wasm's linear memory
  return bytes.length;
}

function readString(memory, ptr, len) {
  return new TextDecoder().decode(new Uint8Array(memory.buffer, ptr, len));
}

const wasm = new WebAssembly.Instance(new WebAssembly.Module(MEM_WASM)).exports;

function shout(text) {
  const len = writeString(wasm.memory, 16, text);
  wasm.upper(16, len); // wasm changes the bytes in place
  return readString(wasm.memory, 16, len);
}

function byteSum(text) {
  const len = writeString(wasm.memory, 16, text);
  return wasm.sum_bytes(16, len);
}

The rest of this lesson

  • Views over one bufferexplain
  • Pitfalls of shared memoryexplain
  • Calling wasm with a stringorder
  • JS tool for the jobmatch
  • Call wasm with stringswrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 8 lessons of WebAssembly