zigar.io.redirect(fn_ptr) - chung-leong/zigar GitHub Wiki
Apply IO redirection to the dynamically linked library that contains the function referenced by
fn_ptr. Not available for WebAssembly.
Usage:
const std = @import("std");
const zigar = @import("zigar");
pub fn call(path: []const u8, fn_name: [:0]const u8) !void {
var lib = try std.DynLib.open(path);
defer lib.close();
const fn_ptr = lib.lookup(*const fn () void, fn_name) orelse return error.UnableToFindFunction;
try zigar.io.redirect(fn_ptr);
fn_ptr();
}
// source code for dynamically linked library
const std = @import("std");
export fn print() void {
std.debug.print("Hello world\n", .{});
}
import { platform } from 'node:os';
import { fileURLToPath } from 'node:url';
import { __zigar, call } from './io-redirection-example-1.zig';
const { on } = __zigar;
let ext;
switch (platform()) {
case 'win32': ext = 'dll'; break;
case 'darwin': ext = 'dynlib'; break;
default: ext = 'so'; break;
}
on('log', (evt) => {
console.log(evt);
return true;
});
const path = fileURLToPath(new URL(`./lib/print.${ext}`, import.meta.url));
call(path, 'print');
{ source: 'stderr', message: 'Hello world' }
Note:
The Zig module should be the only code using the library in question. Do not redirect libraries used by Node.js.
The above example would not work on Linux on ARM if the dynamically linked library does not use libc. Redirection of direct system calls relies on syscall user dispatch, a kernel feature excluse to x86.