liveBook · Manning

WebAssembly memory

As explained in Refactoring to Rust

WebAssembly memory is a resizable byte-addressable storage region associated with a WebAssembly module and accessible through the host interface.

WebAssembly memory is a simple, resizable ArrayBuffer containing raw bytes. A module and its host VM share this memory, while each module receives its own allocation and pointer context. Because WebAssembly has no string or character primitives, values crossing the boundary must be represented as bytes. section 10.6

A host application and module must agree on a low-level exchange sequence:

  • Allocate space in module memory. section 10.6
  • Retrieve the allocated location and write input bytes into it. section 10.6
  • Invoke the module function using the agreed memory location. section 10.6
  • Read the result bytes from the returned memory location. section 10.6

Passing a search term through memory

An exported Rust allocator creates a Vec with capacity, returns its pointer, and prevents the buffer from being dropped. A memory_search function then reads a C string from that pointer, converts the bytes into a String, performs the search, converts the first result back into bytes, pads it to 1024 bytes, and returns a C-compatible pointer. The host VM obtains the module's memory and allocate function before calling the search function. section 10.6 section 10.6

Figure 10.6 Wasm memory
figure

Use the memory diagram to trace how the VM and module share an allocation while retaining separate module execution contexts. section 10.6

Figure 10.8 Wasm reading and writing to the memory buffer
figure

Use the buffer diagram to follow input writing and result reading across the host-module boundary. section 10.6

How Refactoring to Rust covers it

How deep it goes
Explains raw-byte storage, growth, allocation, pointers, and read/write exchange, then demonstrates Rust bindings without detailing every memory instruction.
Examples
Uses allocator and memory_search functions, search-term byte conversion, padded results, VM registration, and memory-buffer diagrams.
What it assumes
Introduces systems-level memory management for developers who may not normally handle allocation, pointers, and raw byte buffers.
What you can do after
Operate/configure a VM memory interface by allocating a buffer, exchanging bytes, invoking an exported function, and reading output.
How it connects
Ties module memory to WebAssembly modules, virtual machines, host runtimes, pointers, allocation, and C-compatible strings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.