v8 - 如何在 d8 上运行 wasm

标签 v8 webassembly

我有一个 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/

相关文章:

c# - Blazor WebAssembly 应用程序/身份验证/注销导致 "There was an error trying to log you out: ' '"失败

c# - Auth0 Blazor 从源 'https://dev-xx.us.auth0.com/oauth/token' 获取 'https://xx.azurewebsites.net' 的访问已被 CORS 策略阻止

JavaScript 返回语句意外

linux - 使用 Forever 和 --prof 选项启动 Node V8 未创建日志文件

v8 - 什么是v8旧空间和新空间?

c++ - 基本示例的 V8 编译错误

javascript - 我可以使用 WebAssembly 在我的 Web 应用程序中安全地执行不受信任的用户代码吗?

javascript - 包含标准库时出现 WebAssembly LinkError

rust - 如何将 and_then 链分成两部分?

javascript - 在 V8 Javascript 引擎中,如何使用 C++ API 添加一个 FunctionTemplate 作为另一个 FunctionTemplate 的属性?