WebAssembly

Zig supports building for WebAssembly out of the box. There is also a specialized std.heap.wasm_allocator memory allocator for WebAssembly environments.

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. const args = try std.process.argsAlloc(std.heap.wasm_allocator);
  4. defer std.process.argsFree(std.heap.wasm_allocator, args);
  5. for (args) |arg, i| {
  6. std.debug.warn("{}: {}\n", i, arg);
  7. }
  8. }
  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