“WebAssembly natively understands only numeric primitives (i32, i64, f32, f64). To pass strings, JSON, or complex objects, strings must be encoded as UTF-8 bytes into Linear Memory, passing (ptr, len) coordinate pairs across the foreign function interface (FFI).”
Encoding UTF-8 strings into Linear Memory, passing pointers, and decoding return buffers.
(module
(memory (export "memory") 1)
;; Stores "WASM" (0x57, 0x41, 0x53, 0x4d) in data section at offset 0
(data (i32.const 0) "WASM")
(func $getStringPtr (result i32)
i32.const 0)
(func $getStringLen (result i32)
i32.const 4)
(export "getStringPtr" (func $getStringPtr))
(export "getStringLen" (func $getStringLen))
)const { instance } = await WebAssembly.instantiate(wasmBytes);
const ptr = instance.exports.getStringPtr();
const len = instance.exports.getStringLen();
const bytes = new Uint8Array(instance.exports.memory.buffer, ptr, len);
const str = new TextDecoder().decode(bytes);
console.log('Decoded Wasm String:', str); // "WASM"JavaScript encodes string using TextEncoder: const bytes = new TextEncoder().encode("Hello")
Calls Wasm allocator function (e.g. malloc(bytes.length)) to receive memory pointer ptr
Copies encoded bytes into new Uint8Array(wasmMemory.buffer, ptr, bytes.length)
Invokes Wasm function passing ptr and bytes.length as arguments
Decodes return buffer using TextDecoder: new TextDecoder().decode(subArray)
Tools like wasm-bindgen automate pointer allocation, UTF-8 transcoding, and cleanup with zero boilerplate.