WebAssembly
创建 WebAssembly 源代码: 创建一个简单的 C 文件(例如 example.c),其中包含一个简单的函数,它将两个数字相加:
c
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
编译成 wasm 文件: emcc example.c -o example.wasm
或者编译输出 html 文件 ./emcc example.c -o index.html
。打开html 文件目录 npx serve -p 3000
这将生成 example.wasm 文件
导出 ES 模块
emcc -o hello.js hello.c -s MODULARIZE=1
没有直接支持的 es 模块,需要手动调整,加上
Javascript
var Module = (() => {
var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
if (typeof __filename !== 'undefined') _scriptDir ||= __filename;
return function (moduleArg = {}) {
//
};
})();
if (typeof exports === 'object' && typeof module === 'object') module.exports = Module;
else if (typeof define === 'function' && define['amd']) define([], () => Module);
没有直接支持的 es 模块,需要手动调整,加上
const exportModule = Module();
export default exportModule;
// for debug use
globalThis.wasm = exportModule;
async function echo(event) {
await wasmModule.ready;
wasmModule._echo();
}
创建 HTML 文件: 创建一个 HTML 文件(例如 index.html),并在其中加载并运行 wasm 文件:
Assembler
Nasm https://www.nasm.us
Emscripten
https://emscripten.org/docs/introducing_emscripten/about_emscripten.html
bash
git clone https://github.com/emscripten-core/emsdk.git
# Fetch the latest version of the emsdk (not needed the first time you clone)
git pull
# Download and install the latest SDK tools.
./emsdk install latest
# Make the "latest" SDK "active" for the current user. (writes .emscripten file)
./emsdk activate latest
# Activate PATH and other environment variables in the current terminal
source ./emsdk_env.sh
Debug
https://developer.chrome.com/blog/wasm-debugging-2020/
编译优化
https://jeromewu.github.io/improving-performance-using-webassembly-simd-intrinsics/