How to use WebAssembly from node.js?

后端 未结 2 1141
栀梦
栀梦 2020-12-16 03:15

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

2条回答
  •  不知归路
    2020-12-16 04:19

    Thanks @sven. ( translate only )

    test.c:

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

    compiling:

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

    test.js:

    const util = require('util');
    const fs = require('fs');
    var source = fs.readFileSync('./test.wasm');
    const env = {
      __memory_base: 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(10, 9));
    }).catch(e => {
      // error caught
      console.log(e);
    });
    

提交回复
热议问题