WebAssembly Memory and Strings
A string is text, and Wasm memory holds only bytes. So JavaScript encodes the string into bytes and copies those bytes into memory first.
Sum bytes in Wasm
This function reads bytes from memory. It adds each byte and returns the total.
(module
(memory (export "memory") 1)
(func (export "sum") (param i32 i32) (result i32)
(local i32 i32)
(local.set 2 (i32.const 0))
(local.set 3 (i32.const 0))
(block $exit
(loop $loop
(br_if $exit (i32.ge_u (local.get 2) (local.get 1)))
(local.set 3
(i32.add (local.get 3)
(i32.load8_u (i32.add (local.get 0) (local.get 2)))))
(local.set 2 (i32.add (local.get 2) (i32.const 1)))
(br $loop)))
(local.get 3)))Encode a string into memory
TextEncoder turns Hi into the bytes 72 and 105. The view copies them to address 0.
const view = new Uint8Array(instance.exports.memory.buffer);
const bytes = new TextEncoder().encode("Hi");
view.set(bytes, 0);
console.log(instance.exports.sum(0, 2));One call for the whole string
ABC encodes to 65, 66, and 67. One sum call adds all three at once.
const view = new Uint8Array(instance.exports.memory.buffer);
const bytes = new TextEncoder().encode("ABC");
view.set(bytes, 0);
console.log(instance.exports.sum(0, 3));Example
(async () => {
const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABQMBAAEHEAIGbWVtb3J5AgADc3VtAAAKMwExAQJ/QQAhAkEAIQMCQANAIAIgAU8NASADIAAgAmotAABqIQMgAkEBaiECDAALCyADCw==";
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes);
const view = new Uint8Array(instance.exports.memory.buffer);
view.set(new TextEncoder().encode("Hi"), 0);
console.log(instance.exports.sum(0, 2));
view.set(new TextEncoder().encode("ABC"), 0);
console.log(instance.exports.sum(0, 3));
})();Key points
- Wasm memory holds bytes, not strings.
- TextEncoder turns a string into bytes.
- Copy the bytes into memory at a known address.
- Pass the address and the length to Wasm.
- Pass big buffers across, not one call per item.
In this example, the bytes are decoded and started into an instance. Then Hi is encoded to 72 and 105 and copied to address 0, so sum gives 177. Then ABC is encoded to 65, 66, and 67 and copied to address 0, so sum gives 198.
Note
The bytes stay in memory until something overwrites them.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
How does JavaScript pass a string to Wasm?