您的位置:首页 > Web前端 > JavaScript

[WASM] Read WebAssembly Memory from JavaScript

2017-06-29 19:59 483 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐