本文介绍了如何从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:

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

08-29 07:36