我有一个 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 中,由于 fetch 没有实现,我们可以这样做
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;
关于v8 - 如何在 d8 上运行 wasm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61747815/