【问题标题】:How to use WebAssembly with Node.js如何在 Node.js 中使用 WebAssembly
【发布时间】:2018-11-18 20:49:14
【问题描述】:

我从 stackoverflow 链接获得了这段代码:

How to use WebAssembly from node.js?

创建一个test.c文件:

int add(int a, int b) {
  return a + b;
}  

构建独立的 .wasm 文件

emcc test.c -O2 -s WASM=1 -s SIDE_MODULE=1 -o test.wasm  

在 Node.js 应用程序中使用 .wasm 文件:

const util = require('util');
const fs = require('fs');
var source = fs.readFileSync('./test.wasm');
const env = {
    memoryBase: 0,
    tableBase: 0,
    memory: new WebAssembly.Memory({
      initial: 256
    }),
    table: new WebAssembly.Table({
      initial: 0,
      element: 'anyfunc'
    })
  }

var typedArray = new Uint8Array(source);

WebAssembly.instantiate(typedArray, {
  env: env
}).then(result => {
  console.log(util.inspect(result, true, 0));
  console.log(result.instance.exports._add(9, 9));
}).catch(e => {
  // error caught
  console.log(e);
});  

使用

启动 Node.js 服务器时出现错误
node Node.js  

LinkError: WebAssembly Instantiation: Import #3 module="env" function="abort" error: function import requires a callable

【问题讨论】:

    标签: node.js webassembly


    【解决方案1】:

    使用您自己的自定义代码加载由 emscripten 生成的 SIDE_MODULE 会很棘手,因为您使用 emscripten 构建的模块需要由 emscripten 生成的 JavaScript 作为宿主。如果为了使它工作,你将需要提供一个兼容的环境。如果可能更容易删除 SIDE_MODULE 并让 emscripten 使用 -o <something>.js 为您输出 js 模块,这将生成 wasm 文件和加载它的 js 文件。

    如果您确实想继续手写加载代码,看起来您需要做的第一件事是私有并在您传递给实例化的env 中实现abort 函数。您很可能还需要其他功能,并且此界面可能会随着 emscripten 的发展而改变。

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2021-02-26
      • 2021-02-27
      相关资源
      最近更新 更多