WebAssembly

WebAssembly

Posted by nomadli on October 10, 2022

环境

LLVM IR to object files x.o

llc -march=wasm32 -filetype=obj x.ll

Linking

wasm-ld –no-entry –export-all -o x.wasm x.o # –no-entry 无入库函数 # –export-all 导出所有符号

run

wasmtime x.wasm –invoke function_name param1 param2 …

#或 #llvm-ar llvm-nm llvm-strip llvm-ranlib #LDFLAGS=${LDFLAGS} -Wl,–no-threads clang –target=wasm32 -O3 -s -flto -nostdlib -Wl,–no-entry -Wl,–export-all -Wl,–lto-O3 -o x.wasm x.c # –target=wasm32 目标平台 # -O3 编译优化级别 # -flto 添加原数据 # -nostdlib 不链接stdlib 不需要 sysroot # -Wl,–no-entry 无入口函数 # -Wl,–export-all 符号全部导出 # -Wl,–lto-O3 链接优化级别

使用wasi标准C库

clang –target=wasm32-unknown-wasi –sysroot /x/wasi-libc -O3 -s -o x.wasm x.c

C++不支持异常 CXX_FLAGS=-fno-exceptions

fetch(‘./x.wasm’).then(function(response) { return response.arrayBuffer() }).then(function(bytes) { return WebAssembly.instantiate(bytes) }).then(function(results) { const add = results.instance.exports.add; var result = add(1, 2); }).catch(console.error); ```