我有一个wasm文件fib.wasm,其中包含函数fib(n)。如果在浏览器中运行它,我们可以执行
var module, functions = {};
fetch('fib.wasm')
.then(response => response.arrayBuffer())
.then(buffer => new Uint8Array(buffer))
.then(binary => {
var moduleArgs = {
wasmBinary: binary,
onRuntimeInitialized: function () {
functions.fib =
module.cwrap('fib',
'number',
['number']);
onReady();
}
};
module = Module(moduleArgs);
});
如果在Node中,由于未实现获取,我们可以这样做
const fs = require('fs')
const buf = fs.readFileSync('fib.wasm')
(async () => { res = await WebAssembly.instantiate(buf); })()
const { fib } = res.instance.exports
但是,在d8 shell中,两种方式都涉及未定义的函数。我们如何在d8中运行wasm?
d8
Shell具有函数read()
,该函数从磁盘读取文件。它需要一个可选参数来指定二进制模式。所以以下应该工作:
const buf = read('fib.wasm', 'binary');
let res;
WebAssembly.instantiate(buf).then((x) => res = x, (error) => console.log(error));
const { fib } = res.instance.exports;