Code
webassembly
// Shared memory bridge for string passing
const memory = instance.exports.memory;
const encoder = new TextEncoder();
const decoder = new TextDecoder();
// Write a JS string into WASM memory at a pointer
function writeString(str, ptr) {
const bytes = encoder.encode(str);
const view = new Uint8Array(memory.buffer, ptr, bytes.length);
view.set(bytes);
return bytes.length;
}
// Read a string out of WASM memory
function readString(ptr, len) {
const view = new Uint8Array(memory.buffer, ptr, len);
return decoder.decode(view);
}
const len = writeString("hello wasm", 0);
console.log(readString(0, len)); // hello wasm