如何从node.js使用WebAssembly? [英] How to use WebAssembly from node.js?

查看:100
本文介绍了如何从node.js使用WebAssembly?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理个人Node.js(> = 8.0.0)项目,该项目要求我调用C子例程(以缩短执行时间).我正在尝试使用WebAssembly进行此操作,因为在浏览器中打开后,我需要最终代码兼容.

I am currently working on a personal Node.js (>=8.0.0) project which requires me to call C subroutines (to improve execution time). I am trying to use WebAssembly to do this since I need my final code to be compatible when opened in a browser.

我已经使用Emscripten将C代码编译为WebAssembly,但不知道如何进行此操作.

I have used Emscripten to compile C code into WebAssembly, and do not know how to proceed after this.

任何在正确方向上的帮助都将非常有用.谢谢!

Any help in the right direction would be great. Thanks!

推荐答案

您可以构建.wasm文件(独立),而没有JS粘合文件.有人回答了类似的问题.

You can build a .wasm file (standalone) without JS glue file. Someone has answered the similar question.

创建一个test.c文件:

Create a test.c file:

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

构建独立的.wasm文件:

Build the standalone .wasm file:

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

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

Use the .wasm file in Node.js app:

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);
});

关键部分是WebAssembly.instantiate().没有它,您将收到错误消息:

The key part is the second parameter of WebAssembly.instantiate(). Without it, you will get the error message:

TypeError:WebAssembly实例化:Imports参数必须存在并且必须是一个对象在在process._tickCallback(内部/进程/next_tick.js:188:7)在Function.Module.runMain(module.js:695:11)在启动时(bootstrap_node.js:191:16)在bootstrap_node.js:612:3

TypeError: WebAssembly Instantiation: Imports argument must be present and must be an object at at process._tickCallback (internal/process/next_tick.js:188:7) at Function.Module.runMain (module.js:695:11) at startup (bootstrap_node.js:191:16) at bootstrap_node.js:612:3

这篇关于如何从node.js使用WebAssembly?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆