WebAssembly
Zig 将 WebAssembly (Wasm) 视为一等公民。它可以直接编译为 Wasm 模块,支持 freestanding 和 WASI 环境。
编译为 Wasm
使用 -target wasm32-freestanding 或 -target wasm32-wasi 进行编译。
$ zig build-exe math.zig -target wasm32-freestanding -rdynamic
Freestanding
在 Freestanding 环境中,没有操作系统。你需要手动导出函数供宿主环境(如浏览器中的 JS)调用,并可能需要导入宿主环境提供的函数。
export fn add(a: i32, b: i32) i32 {
return a + b;
}
WASI (WebAssembly System Interface)
WASI 提供了一套类似 POSIX 的系统调用接口,使得 Wasm 模块可以进行文件 I/O、网络通信等操作(如果运行时支持)。
const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello from WASI!\n", .{});
}
编译并运行(使用 wasmtime):
$ zig build-exe hello.zig -target wasm32-wasi
$ wasmtime hello.wasm
Hello from WASI!