Skip to content
WebAssembly

JS Interop

Pass strings through shared memory.

By EZ4Code Team
interopstringmemory

Code

// 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

Explanation

WebAssembly has no string type, so strings are exchanged by encoding them into UTF-8 bytes in linear memory and passing the pointer and length between JS and WASM. TextEncoder and TextDecoder handle the UTF-8 conversion, and typed array views access the bytes. Always recompute views after any memory grow.

More WebAssembly Snippets