[WASM] Read WebAssembly Memory from JavaScript

We use an offset exporting function to get the address of a string in WebAssembly memory. We then create a typed array on top of the WebAssembly memory representing the raw string data, and decode that into a JavaScript string.

WASM Fiddle: https://wasdk.github.io/WasmFiddle/?6wzgh

Demo Repo: https://github.com/guybedford/wasm-intro

 

C code:

char str[] = "Hello World";

char* getStrOffset () {
  return &str[0];
}

Here we created a pointer, point to the first chat of the string array.

 

When we compile the C code to the WASM:

(module
  (table 0 anyfunc)
  (memory $0 1)  
  (data (i32.const 16) "Hello World\00")
  (export "memory" (memory $0)) # export memory to JS
  (export "getStrOffset" (func $getStrOffset))
  (func $getStrOffset (result i32)
    (i32.const 16) # getStrOffset function return the address in memory as i32.const 16
  )
)

 

Now inside JS, we can get the "memory":

var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);

const memory = wasmInstance.exports.memory;

And remember that it points to the first chat's address in memory.

So we can use Unit8Array to read buffer:

const strBuf = new Uint8Array(memory.buffer, wasmInstance.exports.getStrOffset(), 11); // read biffer from the memory, getStrOffset return the first chat address, and since string (Hello World) is 11 lenght
const str = new TextDecoder().decode(strBuf);
log(str); // Hello World

 

posted @ 2017-06-29 19:59  Zhentiw  阅读(573)  评论(0)    收藏  举报