Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebAssembly #321

Open
xlearns opened this issue Jul 11, 2023 · 0 comments
Open

WebAssembly #321

xlearns opened this issue Jul 11, 2023 · 0 comments

Comments

@xlearns
Copy link
Owner

xlearns commented Jul 11, 2023

Emscripten 安装

  • 如果git clone 失败则需要给终端配置代理

window

  • git clone https://github.com/emscripten-core/emsdk.git
  • cd emsdk
  • .\emsdk.bat update
  • .\emsdk.bat install latest
  • .\emsdk.bat activate latest
  • .\emsdk_env.bat
  • emcc -v

linux

  • git clone https:github.com/emscripten-core/emsdk.git
  • CD EMSDK
  • ./emsdk update
  • ./emsdk install latest
  • ./emsdk activate latest
  • ./emsdk_env.sh
  • emcc -v

将C/C++ 编译成wasm

  • 'EXPORTED_FUNCTIONS':导出函数需要加上_
emcc example.cpp -o example.js -s EXPORTED_FUNCTIONS="['_add']"
  • 如果是cpp文件则需要给函数去除重载的影响
    • extern "C" {}
#include <stdio.h>

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


int main() {
  return 0;
}

  • 浏览器使用
<!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>

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant