Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 · Compiling from C, Rust and Others

Passing Strings and Structs Across the Boundary

Learn how strings, arrays and structs cross the JavaScript and WebAssembly boundary - UTF-8 encoding, pointer and length pairs, allocation, alignment and endianness, with runnable code.

WebAssembly functions take and return only four numeric types. There is no string type, no array type and no object type in the core instruction set. Yet real programs pass text and records back and forth all the time. The solution is always the same: put the data in linear memory and pass its address. Every compiler and every glue generator, whether Emscripten, wasm-bindgen or a hand-written loader, is a variation on this one idea.

Understanding it once means you can read any generated glue code, debug a corrupted string, and write fast, copy-free interfaces yourself. This lesson works through strings first (the most common case), then structs and their memory layout.

The recipe: pointer plus length

To give a string to a wasm function:

  1. Encode it as bytes (almost always UTF-8).
  2. Ask the module for a block of memory big enough (alloc / malloc).
  3. Copy the bytes in.
  4. Call the function with the pointer and the length.
  5. Free the block when done.

Receiving a string is the same in reverse: the function returns a pointer and a length (two numbers, so it needs either two return values, an out-parameter, or a packed i64), and JavaScript decodes that slice of memory.

Sending a string to Wasm

Encode TextEncoder gives UTF-8 bytes.
Allocate Ask the module for space.
Copy Write bytes at the pointer.
Call Pass pointer and length.

Free the block afterwards.

1 / 2

A module with an allocator and string helpers

The module in the next example exports memory, a tiny bump allocator alloc(n) (it hands out consecutive blocks and never frees until reset()), an in-place upper(ptr, len) that uppercases ASCII letters, and count_byte(ptr, len, byte). Its text-format source is summarized in the comments.

Node.js Send a string, change it in place, read it back

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.

Pay attention to step 3. The view new Uint8Array(wasm.memory.buffer, ptr, len) is created after the allocation. If alloc had grown the memory, a view made earlier would be detached. Making the view at the moment you need it is the safe habit.

UTF-8 length is not string length

A JavaScript string.length counts UTF-16 code units. The wasm function wants bytes. For plain ASCII they agree, but for anything else they do not, and mixing them up truncates or overruns the text:

Node.js Characters, UTF-16 units and UTF-8 bytes

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 garbled output of the wrong-length decode (a replacement character) is the classic symptom of a length mix-up. Always compute the length from the encoded bytes. TextEncoder.encodeInto(string, view) can write directly into a memory view and tells you how many bytes it wrote, which avoids a temporary array.

Returning strings

When the module produces text, it has to say where. Three common conventions:

Convention How Used by
Return a pointer to a NUL-terminated string JS scans memory until byte 0 C and Emscripten (UTF8ToString)
Return a packed i64 (pointer in the high half, length in the low half) JS unpacks with BigInt Some hand-written ABIs
Multi-value return (i32, i32) JS receives an array [ptr, len] wasm-bindgen with the multi-value feature, component model

Whichever you choose, define who owns the memory. Usually the module allocated it, so JavaScript must call back into a free export after copying the text out.

Structs: layout is a contract

A C or Rust struct becomes a block of bytes. The compiler decides the offset of every field based on size and alignment rules: a 4-byte int must start at an offset divisible by 4, an 8-byte double at a multiple of 8, and the struct as a whole is padded so arrays of it stay aligned. Both sides must agree on this layout.

C
struct Particle {
    int32_t id;      // offset 0, 4 bytes
    // 4 bytes of padding so the next field is 8-aligned
    double  x;       // offset 8, 8 bytes
    uint8_t alive;   // offset 16, 1 byte
    // 7 bytes of padding so sizeof is a multiple of 8
};                   // sizeof(struct Particle) == 24

WebAssembly memory is little-endian, so multi-byte numbers are stored least significant byte first. DataView lets you read and write fields at exact offsets with explicit endianness and no alignment requirement, which makes it ideal for decoding structs:

Node.js Read and write a struct with DataView

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.

Safer alternatives to hand-written layout

  • Let a generator do it: wasm-bindgen for Rust, Emscripten's embind for C++, or the component model with WIT, which defines the layout once for every language (see The Component Model and WIT).
  • Keep the interface narrow: pass flat arrays of numbers and a few scalars instead of nested objects.
  • Prefer copy once, work in wasm, copy back once over many small calls.
  • Share data without copying by creating typed-array views directly over linear memory, as the examples here do. This is also how you pass large arrays and image data efficiently (see Project: Image Filter in WebAssembly).

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What do you pass to a wasm function that should work on a string?

    Wasm only has numeric parameters. The text is encoded, copied into memory, and described by its address and byte length.
  2. 2. 'café'.length is 4. How many UTF-8 bytes does TextEncoder produce for it?

    The letter e with an acute accent takes two bytes in UTF-8, so the text is 5 bytes. Always use the encoded byte length.
  3. 3. Which byte order does WebAssembly linear memory use for multi-byte numbers?

    WebAssembly specifies little-endian, so the least significant byte comes first. DataView methods take a littleEndian flag.
  4. 4. Why are some structs padded?

    Compilers insert padding so a field of size N sits at an offset divisible by N and the struct size is a multiple of its largest alignment.
  5. 5. When should you create a typed-array view over memory.buffer?

    memory.grow replaces the ArrayBuffer. Views created before the growth have length zero afterward.

Summary

  • Strings, arrays and structs cross the boundary as bytes in linear memory plus pointers and lengths.
  • Encode with TextEncoder, allocate in the module, copy, call, decode, and free.
  • Use the UTF-8 byte length, never string.length.
  • WebAssembly memory is little-endian; DataView reads and writes struct fields at exact offsets.
  • Struct layout follows size and alignment rules, so both sides must agree; generators and the component model automate that agreement.

Next: WebAssembly Performance