TExcelTAD
Home › WebAssembly › Passing Strings & Arrays

Passing Strings & Arrays

WebAssembly functions only accept numbers. To pass a string or an array, the host and the module agree on a protocol built on shared linear memory:

  1. Allocate space in the module's memory (by calling an exported alloc).
  2. Copy the data into memory through a typed array view.
  3. Call the function with a pointer and a length.
  4. Read results back from memory (again through a view).

Tools like wasm-bindgen (Rust) and Emscripten's ccall/cwrap generate exactly this glue code for you.

The module for this lesson

wat
(module
  (memory (export "memory") 1)
  (global $top (mut i32) (i32.const 1024))
  ;; bump allocator: returns the old top, then moves it
  (func (export "alloc") (param $n i32) (result i32)
    (global.get $top)
    (global.set $top (i32.add (global.get $top) (local.get $n))))
  ;; ASCII-uppercase $n bytes at $p, in place
  (func (export "upper") (param $p i32) (param $n i32)
    (local $c i32)
    (block $done (loop $next
      (br_if $done (i32.eqz (local.get $n)))
      (local.set $c (i32.load8_u (local.get $p)))
      (if (i32.le_u (i32.sub (local.get $c) (i32.const 97)) (i32.const 25))
        (then (i32.store8 (local.get $p) (i32.sub (local.get $c) (i32.const 32)))))
      (local.set $p (i32.add (local.get $p) (i32.const 1)))
      (local.set $n (i32.sub (local.get $n) (i32.const 1)))
      (br $next))))
  ;; sum of $n f64 values at $p
  (func (export "sum") (param $p i32) (param $n i32) (result f64)
    (local $s f64)
    (block $done (loop $next
      (br_if $done (i32.eqz (local.get $n)))
      (local.set $s (f64.add (local.get $s) (f64.load (local.get $p))))
      (local.set $p (i32.add (local.get $p) (i32.const 8)))
      (local.set $n (i32.sub (local.get $n) (i32.const 1)))
      (br $next)))
    (local.get $s)))

Strings: encode, copy, call, decode

JavaScript strings are UTF-16; Wasm code normally works with UTF-8 bytes. TextEncoder and TextDecoder convert between them:

js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  // types: (i32)->i32, (i32,i32)->(), (i32,i32)->f64
  0x01, 0x11, 0x03, 0x60, 0x01, 0x7f, 0x01, 0x7f, 0x60, 0x02, 0x7f, 0x7f, 0x00, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7c,
  0x03, 0x04, 0x03, 0x00, 0x01, 0x02,                         // functions
  0x05, 0x03, 0x01, 0x00, 0x01,                               // memory: 1 page
  0x06, 0x07, 0x01, 0x7f, 0x01, 0x41, 0x80, 0x08, 0x0b,       // global $top = 1024
  // exports: memory, alloc, upper, sum
  0x07, 0x20, 0x04, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x63,
  0x00, 0x00, 0x05, 0x75, 0x70, 0x70, 0x65, 0x72, 0x00, 0x01, 0x03, 0x73, 0x75, 0x6d, 0x00, 0x02,
  // code (see the WAT above)
  0x0a, 0x76, 0x03, 0x0b, 0x00, 0x23, 0x00, 0x23, 0x00, 0x20, 0x00, 0x6a, 0x24, 0x00, 0x0b,
  0x3c, 0x01, 0x01, 0x7f, 0x02, 0x40, 0x03, 0x40, 0x20, 0x01, 0x45, 0x0d, 0x01, 0x20, 0x00, 0x2d, 0x00, 0x00,
  0x21, 0x02, 0x20, 0x02, 0x41, 0xe1, 0x00, 0x6b, 0x41, 0x19, 0x4d, 0x04, 0x40, 0x20, 0x00, 0x20, 0x02, 0x41,
  0x20, 0x6b, 0x3a, 0x00, 0x00, 0x0b, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x20, 0x01, 0x41, 0x01, 0x6b,
  0x21, 0x01, 0x0c, 0x00, 0x0b, 0x0b, 0x0b,
  0x2b, 0x01, 0x01, 0x7c, 0x02, 0x40, 0x03, 0x40, 0x20, 0x01, 0x45, 0x0d, 0x01, 0x20, 0x02, 0x20, 0x00, 0x2b,
  0x03, 0x00, 0xa0, 0x21, 0x02, 0x20, 0x00, 0x41, 0x08, 0x6a, 0x21, 0x00, 0x20, 0x01, 0x41, 0x01, 0x6b, 0x21,
  0x01, 0x0c, 0x00, 0x0b, 0x0b, 0x20, 0x02, 0x0b,
]);
const { instance } = await WebAssembly.instantiate(bytes);
const { memory, alloc, upper } = instance.exports;

function shout(text) {
  const encoded = new TextEncoder().encode(text);          // 1. UTF-8 bytes
  const ptr = alloc(encoded.length);                       // 2. room in Wasm memory
  new Uint8Array(memory.buffer, ptr, encoded.length).set(encoded);   // 3. copy in
  upper(ptr, encoded.length);                              // 4. call with (ptr, len)
  const out = new Uint8Array(memory.buffer, ptr, encoded.length);    // 5. read back
  return [ptr, new TextDecoder().decode(out)];
}

console.log(shout('hello, wasm'));
console.log(shout('café crème'));        // é is 2 bytes and isn't ASCII, so it is untouched
console.log('next free address:', alloc(0));
[ 1024, 'HELLO, WASM' ]
[ 1035, 'CAFé CRèME' ]
next free address: 1047

The second string is 10 characters but 12 bytes, so the next allocation starts at 1024 + 11 + 12 = 1047. Always use the byte length (encoded.length), never text.length.

Tip: TextEncoder.encodeInto(text, view) encodes directly into Wasm memory without an intermediate array.

Arrays of numbers

For numeric arrays, a typed array of the matching type (Float64Array for f64, Int32Array for i32) views the memory directly. Its byte offset must be a multiple of the element size, so allocate aligned space:

js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x11, 0x03, 0x60, 0x01, 0x7f, 0x01, 0x7f, 0x60, 0x02, 0x7f, 0x7f, 0x00, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7c,
  0x03, 0x04, 0x03, 0x00, 0x01, 0x02, 0x05, 0x03, 0x01, 0x00, 0x01, 0x06, 0x07, 0x01, 0x7f, 0x01, 0x41, 0x80, 0x08, 0x0b,
  0x07, 0x20, 0x04, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x05, 0x61, 0x6c, 0x6c, 0x6f, 0x63,
  0x00, 0x00, 0x05, 0x75, 0x70, 0x70, 0x65, 0x72, 0x00, 0x01, 0x03, 0x73, 0x75, 0x6d, 0x00, 0x02,
  0x0a, 0x76, 0x03, 0x0b, 0x00, 0x23, 0x00, 0x23, 0x00, 0x20, 0x00, 0x6a, 0x24, 0x00, 0x0b,
  0x3c, 0x01, 0x01, 0x7f, 0x02, 0x40, 0x03, 0x40, 0x20, 0x01, 0x45, 0x0d, 0x01, 0x20, 0x00, 0x2d, 0x00, 0x00,
  0x21, 0x02, 0x20, 0x02, 0x41, 0xe1, 0x00, 0x6b, 0x41, 0x19, 0x4d, 0x04, 0x40, 0x20, 0x00, 0x20, 0x02, 0x41,
  0x20, 0x6b, 0x3a, 0x00, 0x00, 0x0b, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x20, 0x01, 0x41, 0x01, 0x6b,
  0x21, 0x01, 0x0c, 0x00, 0x0b, 0x0b, 0x0b,
  0x2b, 0x01, 0x01, 0x7c, 0x02, 0x40, 0x03, 0x40, 0x20, 0x01, 0x45, 0x0d, 0x01, 0x20, 0x02, 0x20, 0x00, 0x2b,
  0x03, 0x00, 0xa0, 0x21, 0x02, 0x20, 0x00, 0x41, 0x08, 0x6a, 0x21, 0x00, 0x20, 0x01, 0x41, 0x01, 0x6b, 0x21,
  0x01, 0x0c, 0x00, 0x0b, 0x0b, 0x20, 0x02, 0x0b,
]);
const { instance } = await WebAssembly.instantiate(bytes);
const { memory, alloc, sum } = instance.exports;

function sumInWasm(values) {
  const ptr = alloc(values.length * 8);                    // 1024 is 8-aligned
  const view = new Float64Array(memory.buffer, ptr, values.length);
  view.set(values);
  return sum(ptr, values.length);
}

const prices = [19.99, 5.25, 100, 0.76];
console.log(sumInWasm(prices));
console.log(sumInWasm([1.5, 2.5, 3.5]));

// what the bytes of the first array look like
const first = new Float64Array(memory.buffer, 1024, 4);
console.log(Array.from(first));

try {
  new Float64Array(memory.buffer, 1027, 1);                // misaligned view
} catch (err) {
  console.log(err.constructor.name);
}
126
7.5
[ 19.99, 5.25, 100, 0.76 ]
RangeError

The JavaScript view must be aligned (a RangeError otherwise), even though Wasm itself accepts misaligned loads.

Returning strings from Wasm

A Wasm function can't return a string either. Common conventions:

Convention How it works
Write into a caller buffer JS allocates, Wasm writes and returns the number of bytes written
Return a pointer + length with multi-value: (result i32 i32), or write both to a known address
Zero-terminated return a pointer; JS scans for the 0 byte (C style)
Callback Wasm calls an imported console.str(ptr, len), as our playground does

Who frees the memory?

Our bump allocator never frees. Real modules export alloc/free (or malloc/free from C), and the glue code must free every buffer it allocated, usually in a try … finally. Forgetting this leaks Wasm memory, which never shrinks. wasm-bindgen handles it automatically for strings and Vecs.

Test yourself

How many bytes must you allocate to pass the JS string "café" as UTF-8?

  1. 4
  2. 5
  3. 8
  4. It depends on the engine

Which API converts a JS string to UTF-8 bytes?

  1. String.prototype.charCodeAt
  2. TextEncoder
  3. JSON.stringify
  4. btoa

Why must the pointer for a Float64Array view be a multiple of 8?

  1. Wasm traps otherwise
  2. Typed arrays require their byte offset to be a multiple of the element size
  3. Memory pages are 8 bytes
  4. It doesn't have to be