Skip to content

Special exports __zigar

Chung Leong edited this page Apr 24, 2024 · 4 revisions

Zigar exposes certain utility functions through the symbol __zigar:

init()

Return a promise that resolves when WebAssembly code finishes compiling and all Zig functions can be called synchronously.

const std = @import("std");

pub fn hello() void {
    std.debug.print("hello\n", .{});
}
import { __zigar, hello } from './special-exports-example-1.zig';
const { init } = __zigar;
hello();
hello

Use of this function is only necessary when topLevelawait is false. For node-zigar, this function is useless. It returns a promise that resolves immediately.

abandon()

Unload the module from memory. Imported functions would no longer work afterward. This function is meant mainly for automated testing where a large number of modules would get loaded and used only once.

import { __zigar, hello } from './special-exports-example-1.zig';
const { abandon } = __zigar;

hello();
abandon();
try {
    hello();
} catch (err) {
    console.log(err.message);
}
hello
Module was abandoned

Unloading does not happen immediately. This function merely removes all references to the module, allowing it to be garbage-collected. It can fail if there're objects allocated from the fixed memory heap sitting somewhere.

released()

Return true if module has been unloaded from memory; false otherwise.

import { __zigar } from './special-exports-example-1.zig';
const { abandon, released } = __zigar;

abandon();
// force garbage collection to occur (need --expose-gc)
gc();   
// give V8 a chance to invoke object finalizers
await new Promise(r => setTimeout(r, 0));
console.log(released());

connect(c)

Use a different console object to display output to stdout and stderr. Only its log method will get called, always with a single string as argument.

import { __zigar, hello } from './special-exports-example-1.zig';
const { connect } = __zigar;

connect({
    log(s) {
        console.log(`Zig output: "${s}"`);
    }
});
hello();
Clone this wiki locally