参考连接

  1. https://zhuanlan.zhihu.com/p/68048524 知乎文章
  2. https://www.cnblogs.com/sweeeper/p/14361948.html csdn 博客
    1. https://mbebenita.github.io/WasmExplorer/ 在线编译 .wasm 能力
  3. http://webassembly.org.cn/getting-started/developers-guide/ WebAssembly 官网

本地编译

核心代码

test.c 文件

  1. // 在 test.c 文件中定义一个 add 方法
  2. // 因为后面使用JavaScript对C++函数进行调用的时候需要依赖这个名字,
  3. // 为了避免这种问题,可以将编译器选择为C99或者在函数外层增加extern "C"块
  4. extern "C" {
  5. int add(int a, int b){
  6. return a + b;
  7. }
  8. }

test.c编译为 test.wasm 文件

如果是本地编译,你需要先完成上述的 本地编译 环境准备和安装

  1. 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

在项目中使用

  1. // web 项目中
  2. const url = 'test.wasm'
  3. const getExportFunction = async (url) => {
  4. const instance = await fetch(url)
  5. .then((res) => res.arrayBuffer())
  6. .then((bytes) => WebAssembly.compile(bytes))
  7. .then((module) => {
  8. return new WebAssembly.Instance(module).exports
  9. })
  10. return instance
  11. }
  12. getExportFunction(url).then((res) => {
  13. const add = res.add
  14. console.log(add(5, 12)) // => 输出 17
  15. })