运行 C++ 在 Node.js

Running C++ Wasm In Node.js

我在 node.js 中阅读 post 关于 运行ning webassembly 的内容。当我一步一步按照说明操作时,它起作用了。我想用 c++ 而不是 c 来复制它,当我开始用

构建 wasm 时
em++ -O2 test.cpp -s WASM=1 -s SIDE_MODULE=1 -o test.wasm

和运行节点,它没有运行。

我的节点是这样的:

function main(cpp) {
  console.log(cpp.add(10, 29)); //even when i try cpp._add(10, 29) it doesn't work
}

WebAssembly.instantiate(new Uint8Array(fs.readFileSync('./test.wasm')), {
  env: {
    memoryBase: 0,
    tableBase: 0,
    memory: new WebAssembly.Memory({
      initial: 256
    }),
    table: new WebAssembly.Table({
      initial: 0,
      element: 'anyfunc'
    })
  }
})
.then(result => {
  main(result.instance.exports)
})
.catch(e => console.log(e));

我的 C++ 代码看起来和其他 post 显示的完全一样。

事实证明这是一个简单的错误。在 C 中,函数名是我在文件中声明的,而在 C++ 中,它变成了一串字符(在我的例子中:_Z3addii)。当我做同样的事情时,除了将 cpp.add 替换为 cpp._Z3addii 它起作用了。