C++构建WASM包括库
我正在为包括cmath库在内的错误编译WASM而苦苦挣扎。
我需要做的就是能够在JavaScript中使用SQRT函数...如果我删除SQRT功能和CMATH库,所有这些都可以正常工作...有人可以帮助我了解我在做错了什么吗?
在这里,C ++代码:
#include <cmath>
extern "C" {
int Sum(int a, int b) {
return a + b;
}
int sub (int a, int b){
return a - b;
}
double root (int a){
return sqrt(a);
}
}
这是我在终端上运行的wasm文件,
em++ -std=c++2b "PATH_TO_CPP_FILE" -Oz -s WASM=1 -s SIDE_MODULE=1 -s BINARYEN_ASYNC_COMPILATION=0 -o "PATH_TO_A_FOLDER\FILENAME.wasm"
这是我使用的JavaScript代码:
const importObject = {
module: {},
env: {
memory: new WebAssembly.Memory({ initial: 256 }),
}
};
WebAssembly.instantiateStreaming(
fetch('main.wasm'),
importObject
).then(result => {
const Sum = result.instance.exports.Sum;
const sub = result.instance.exports.sub;
console.log(Sum(4, 5));
console.log(Sum(10, 10));
console.log(sub(20, 10));
});
最后,这是我当前有的错误:
Uncaught (in promise) LinkError: WebAssembly.instantiate(): Import #0 module="env" function="_Z4sqrtIiENSt3__29enable_ifIXsr3std11is_integralIT_EE5valueEdE4typeES2_" error: function import requires a callable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,基本上,当您尝试在代码中包含一些库时,您需要在JavaScript代码中将该函数以及该功能导入。
简单地将其包含在Env属性上的ImportObject中。
现在,假设您已经在项目中包含了多个库,并且想查看要导入的所有功能。
您可以在
在这里,您可以包含您的WASM文件,并查看您需要导入的所有功能。
另外,您可以在浏览器源选项卡上找到相同的信息,您可以在其中单击WASM文件以检查信息。
So basically when you try to include some library in your code, you need to import that function as well in the javascript code.
Simply you include it in the importObject on env property.
Now let say you have included multiple library in your project and you want to see which all functions to be imported.
You can check it on https://webassembly.github.io/wabt/demo/wasm2wat/
here you can include your wasm file and see all the functions you need to import.
Also you can find the same info on browser sources tab, where you can click on the wasm file to check the information.