Tour of WebAssembly Table of Contents

Logging Text

Let's explore a simple example of logging some text from a WebAssembly program.

We must:

  1. Create some utf-8 compliant text in our program's memory
  2. Determine the length of our text's bytes
  3. Somehow send the starting byte start index and length in bytes of that text data to the host browser so it can call console.log.

Here's an example of what that receiving JavaScript function would look like:

wasm_log(start,len) {
  // extract text from memory location and length
  const utf8dec = new TextDecoder("utf-8");
  let buffer = module.instance.exports.memory.buffer;
  let memory = new Uint8Array(buffer);
  let text = utf8dec.decode(memory.subarray(start,start+len));
  console.log(text);
}