Tour de WebAssembly Tabla de Contenidos

[Untranslated] Reading Text

Let's explore the opposite idea. Imagine we want to give some text to a WebAssembly program.

We must:

  1. Determine the length in bytes of the text we want to pass in.
  2. Allocate some space in our memory of that byte length.
  3. Copy bytes into our program's memory at the start of the space we allocated.
  4. Let the WebAssembly program know we have put some data in it's memory at a specific index and lenth in bytes.

Here's an example of what that initialization looks like:

// Turn "Ferris" into bytes
const utf8enc = new TextEncoder("utf-8");
let text = "Ferris";
let text_bytes = utf8enc.encode(text);

// Allocate enough space for the text
let len = text_bytes.length;
let start = module.instance.exports.wasm_malloc(len);

// Put the text in WebAssembly program's memory
let buffer = module.instance.exports.memory.buffer;
let memory = new Uint8Array(buffer);
memory.set(text_bytes, start);

// Run the program
module.instance.exports.main(start,len);