Wasm only understands numbers
Wasm functions take and return numbers. To pass a string or an array you write its bytes into the module's linear memory — one big ArrayBuffer — and pass a pointer and a length. This JavaScript "glue" is what tools like wasm-bindgen generate for you.
The glue
function writeString(memory, ptr, text) {
const bytes = new TextEncoder().encode(text);
new Uint8Array(memory.buffer).set(bytes, ptr); // a view over wasm's linear memory
return bytes.length;
}
function readString(memory, ptr, len) {
return new TextDecoder().decode(new Uint8Array(memory.buffer, ptr, len));
}
const wasm = new WebAssembly.Instance(new WebAssembly.Module(MEM_WASM)).exports;
function shout(text) {
const len = writeString(wasm.memory, 16, text);
wasm.upper(16, len); // wasm changes the bytes in place
return readString(wasm.memory, 16, len);
}
function byteSum(text) {
const len = writeString(wasm.memory, 16, text);
return wasm.sum_bytes(16, len);
}