WebAssembly

Zig supports building for WebAssembly out of the box.

Freestanding

For host environments like the web browser and nodejs, build as a library using the freestanding OS target. Here's an example of running Zig code compiled to WebAssembly with nodejs.

math.zig

  1. extern fn print(i32) void;
  2. export fn add(a: i32, b: i32) void {
  3. print(a + b);
  4. }
  1. $ zig build-lib math.zig -target wasm32-freestanding

test.js

  1. const fs = require('fs');
  2. const source = fs.readFileSync("./math.wasm");
  3. const typedArray = new Uint8Array(source);
  4. WebAssembly.instantiate(typedArray, {
  5. env: {
  6. print: (result) => { console.log(`The result is ${result}`); }
  7. }}).then(result => {
  8. const add = result.instance.exports.add;
  9. add(1, 2);
  10. });
  1. $ node test.js
  2. The result is 3

WASI

Zig's support for WebAssembly System Interface (WASI) is under active development. Example of using the standard library and reading command line arguments:

wasi.zig

  1. const std = @import("std");
  2. pub fn main() !void {
  3. // TODO a better default allocator that isn't as wasteful!
  4. const args = try std.process.argsAlloc(std.heap.page_allocator);
  5. defer std.process.argsFree(std.heap.page_allocator, args);
  6. for (args) |arg, i| {
  7. std.debug.warn("{}: {}\n", .{i, arg});
  8. }
  9. }
  1. $ zig build-exe wasi.zig -target wasm32-wasi
  1. $ wasmer run wasi.wasm 123 hello
  2. 0: wasi.wasm
  3. 1: 123
  4. 2: hello