xlearns / myblog

1 stars 0 forks source link

WebAssembly #321

Open xlearns opened 1 year ago

xlearns commented 1 year ago

Emscripten 安装

linux

将C/C++ 编译成wasm

extern "C" { int add(int a, int b) { return a + b; } }

int main() { return 0; }

- 浏览器使用
```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script>
      Module = {};
      Module.onRuntimeInitialized = function () {
         const { add, main } = Module.asm;
         console.log(add(1, 2));
         console.log(add(10, 2));
         console.log(add(15, 2));
      };
      // fetch("./hello.wasm")
      //   .then((response) => response.arrayBuffer())
      //   .then((bytes) => WebAssembly.instantiate(bytes))
      //   .then((results) => {
      //     const { add } = results.instance.exports;
      //    console.log(add(1, 2));
      // });
    </script>

    <script src="./example.js"></script>
  </head>
  <body></body>
</html>

参考