Skip to content

Lesson 18 ยท Calling Between JS and Wasm

Passing Strings and Arrays

Learn the pointer and length pattern for strings and arrays in WebAssembly: a bump allocator, TextEncoder, typed array views, returning strings, and the stale-view pitfall.

Exports and imports can only carry numbers. So how does JavaScript hand a name to a greeting function, or a thousand floats to a statistics routine? The answer is the pattern behind every language binding, including wasm-bindgen and Emscripten's ccall: put the data into linear memory, and pass its address and length as numbers.

sequenceDiagram
    participant J as JavaScript
    participant W as Wasm module
    participant M as Linear memory
    J->>W: alloc(byteLength)
    W-->>J: pointer
    J->>M: copy bytes in (typed array view)
    J->>W: countVowels(pointer, length)
    W->>M: read bytes
    W-->>J: result (a number)

For this to work the module needs a way to hand out memory. That is an allocator: a function that returns a free region of a requested size. Real toolchains include malloc and free. The module in this lesson has the simplest allocator, a bump allocator: it keeps a pointer to the next free byte and moves it forward on every request. It never frees individual blocks; reset() frees everything at once. That is perfect for learning and for short-lived work such as "run one request, then reset".

The allocator

WAT
(global $heap (mut i32) (i32.const 1024))      ;; first free address (below it: constants)

(func $alloc (export "alloc") (param $n i32) (result i32)
  (local $p i32) (local $end i32) (local $have i32)
  (local.set $p (global.get $heap))
  ;; round the end up to a multiple of 8 so every block is aligned
  (local.set $end (i32.and (i32.add (i32.add (local.get $p) (local.get $n)) (i32.const 7)) (i32.const -8)))
  (local.set $have (i32.shl (memory.size) (i32.const 16)))     ;; current size in bytes
  ;; if the block does not fit, grow by enough pages; return 0 if growth fails
  ...
  (global.set $heap (local.get $end))
  (local.get $p))

The memory below address 1024 holds two data segments: "Hello, " at address 0 and "!" at address 7, which the greet function will copy from. Alignment matters for arrays of f64: a block that starts at a multiple of 8 can be viewed as a Float64Array (typed arrays require an aligned byte offset).

Strings

Sending a string takes three steps:

  1. TextEncoder turns the JavaScript string into UTF-8 bytes (and tells you the byte length).
  2. alloc(length) reserves room and returns a pointer.
  3. Create a Uint8Array over the memory at that pointer and copy the bytes in.

Getting a string back is the reverse: the function returns a pointer, a second call (or a global) provides the length, and TextDecoder reads the bytes.

Node.js Strings in and out of Wasm memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The comment in putString is the most important line of the lesson: allocate first, then create the view. alloc can grow the memory, which detaches earlier views (you saw this in the linear memory lesson). A view created before the call would be useless afterwards.

Because reverse works byte by byte, it is only right for ASCII text. Reversing UTF-8 byte by byte garbles multi-byte characters, a good example of why the module and JavaScript must agree on what the bytes mean.

Arrays of numbers

Arrays work the same way, with typed arrays on the JavaScript side. A Float64Array has 8 bytes per element, so a request for n doubles allocates n * 8 bytes. Create the typed array view directly on memory.buffer at the returned pointer, and then set() copies in the values. The pointer must be a multiple of the element size, which the allocator's 8-byte alignment guarantees.

Node.js Float64 arrays and the stale-view trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

view.set(data) copies; fresh.slice() copies. A view without a copy is a live window onto Wasm memory: it changes when Wasm writes, and becomes stale when memory grows. Use a view for short, immediate work, and slice() when you need data that outlives the next call.

A reusable helper

In a real project you would wrap this once and never think about it again:

JavaScript
class WasmBuffer {
  constructor(wasm) { this.w = wasm; }
  get u8() { return new Uint8Array(this.w.memory.buffer); }   // always the current buffer
  string(text) {
    const data = new TextEncoder().encode(text);
    const ptr = this.w.alloc(data.length);
    this.u8.set(data, ptr);
    return { ptr, len: data.length };
  }
  read(ptr, len) { return new TextDecoder().decode(this.u8.subarray(ptr, ptr + len)); }
}

The u8 getter builds a new view each time, which makes it impossible to hold a stale one by accident.

Other conventions

Pattern How it works Where you see it
Pointer + length Two numbers per buffer Rust slices, Go, Zig
Null-terminated string One pointer, scan for 0 C and C++ (char *)
Caller-provided buffer JS allocates, Wasm fills, returns the length written read-style APIs, WASI
Out parameters JS passes a pointer where Wasm writes a result int *out in C
Handle table JS keeps an array of objects; Wasm gets an index Games, DOM wrappers

Always check the result of alloc for failure (here it returns 0), and free or reset when you are done. A bump allocator that is never reset grows memory forever, and memory never shrinks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why call alloc before creating the typed array view?

    Growing memory replaces the ArrayBuffer, so a view made before the allocation would be stale.
  2. 2. What must you pass for a string's length?

    Memory holds bytes, so the byte length is the length that matters.
  3. 3. What does a bump allocator do on free?

    A bump allocator only moves a pointer forward, so memory is reclaimed by resetting it, not block by block.
  4. 4. Why does the allocator round blocks to a multiple of 8?

    Typed arrays need an aligned byte offset, and 8-byte alignment suits f64 and i64.

Summary

  • Only numbers cross the boundary, so strings and arrays travel as a pointer plus a length into linear memory.
  • The module provides an allocator (alloc); JavaScript copies bytes in with TextEncoder and typed array views.
  • Allocate first, then create the view; never hold a view across a call that might grow memory.
  • Use slice() for data that must outlive the next call; use fresh views for immediate work.
  • Align blocks to the element size, check alloc for failure and reset or free when done.

Next: Traps and Errors