跳转到内容
语言参考Zig 0.17.0官方原文

Zig 原生支持构建面向 WebAssembly 的程序。

独立环境

对于浏览器、nodejs 等宿主环境,使用独立环境操作系统目标构建可执行文件。以下示例使用 nodejs 运行编译为 WebAssembly 的 Zig 代码。

math.zig
extern fn print(i32) void;
export fn add(a: i32, b: i32) void {
print(a + b);
}
命令行
$ zig build-exe math.zig -target wasm32-freestanding -fno-entry --export=add
test.js
const fs = require('fs');
const source = fs.readFileSync("./math.wasm");
const typedArray = new Uint8Array(source);
WebAssembly.instantiate(typedArray, {
env: {
print: (result) => { console.log(`The result is ${result}`); }
}}).then(result => {
const add = result.instance.exports.add;
add(1, 2);
});
命令行
$ node test.js
The result is 3

WASI

Zig 标准库对 WebAssembly 系统接口提供一等支持。

wasi_args.zig
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const args = try init.minimal.args.toSlice(init.arena.allocator());
for (0.., args) |i, arg| {
std.debug.print("{d}: {s}\n", .{ i, arg });
}
}
命令行
$ zig build-exe wasi_args.zig -target wasm32-wasi
命令行
$ wasmtime wasi_args.wasm 123 hello
0: wasi_args.wasm
1: 123
2: hello

更有趣的例子是从运行时提取预打开目录列表。目前标准库通过 std.fs.wasi.Preopens 支持此功能:

wasi_preopens.zig
const std = @import("std");
pub fn main(init: std.process.Init) void {
for (init.preopens.map.keys(), 0..) |preopen, i| {
std.log.info("{d}: {s}", .{ i, preopen });
}
}
命令行
$ zig build-exe wasi_preopens.zig -target wasm32-wasi
命令行
$ wasmtime --dir=. wasi_preopens.wasm
0: stdin
1: stdout
2: stderr
3: .