如何 运行 wasm on d8

How to run wasm on d8

我有一个包含函数 fib(n) 的 wasm 文件 fib.wasm。 如果在浏览器中运行,我们可以

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;