参考连接
- https://zhuanlan.zhihu.com/p/68048524 知乎文章
- https://www.cnblogs.com/sweeeper/p/14361948.html csdn 博客
- https://mbebenita.github.io/WasmExplorer/ 在线编译 .wasm 能力
- http://webassembly.org.cn/getting-started/developers-guide/ WebAssembly 官网
本地编译
核心代码
test.c
文件
// 在 test.c 文件中定义一个 add 方法
// 因为后面使用JavaScript对C++函数进行调用的时候需要依赖这个名字,
// 为了避免这种问题,可以将编译器选择为C99或者在函数外层增加extern "C"块
extern "C" {
int add(int a, int b){
return a + b;
}
}
将 test.c
编译为 test.wasm
文件
如果是本地编译,你需要先完成上述的 本地编译
环境准备和安装
emcc test.c -Os -s WASM=1 -s SIDE_MODULE=1 -o test.wasm
emcc
就是 Emscripten
编译器,test.c
是我们的输入文件,-Os
表示这次编译需要优化,-s WASM=1
表示输出 wasm 的文件,因为默认的是输出 asm.js
,-s SIDE_MODULE=1
表示就只要这一个模块,不要给我其他乱七八糟的代码,-o test.wasm
是我们的输出文件。
编译成功之后,当前目录下就会生成 test.wasm
。
在项目中使用
// web 项目中
const url = 'test.wasm'
const getExportFunction = async (url) => {
const instance = await fetch(url)
.then((res) => res.arrayBuffer())
.then((bytes) => WebAssembly.compile(bytes))
.then((module) => {
return new WebAssembly.Instance(module).exports
})
return instance
}
getExportFunction(url).then((res) => {
const add = res.add
console.log(add(5, 12)) // => 输出 17
})