我读到this关于在 Node.js 中运行 WebAssembly 的帖子。当我一步一步按照说明进行操作时,它成功了。我想用 c++ 而不是 c 来复制这个,当我开始使用
构建 wasm 时em++ -O2 test.cpp -s WASM=1 -s SIDE_MODULE=1 -o test.wasm
并运行该 Node ,但它没有运行。
我的 Node 如下所示:
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++ 代码看起来与其他帖子显示的完全一样。
最佳答案
事实证明,这是一个简单的错误。在 C 中,函数名称是我在文件中声明的内容,而在 C++ 中,它变成了字符串(在我的例子中:_Z3addii)。当我做了同样的事情,除了用 cpp._Z3addii
替换 cpp.add
时,它起作用了。
关于node.js - 在 Node.js 中运行 C++ Wasm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59779880/