Basic zig dynamic library not working

Zig 0.14.0 fails at building this simple .so and dynamically invoking it.

lib.zig:

pub export fn SetInt(ptr : *i32) void {
	ptr.* = 345;
}

main.zig:

const std = @import("std");

const SetIntFn = *const fn (ptr : *i32) void;

pub fn main() !void {
    var lib = try std.DynLib.open("zig-out/lib/libmathlib.so");
    defer lib.close(); 

    const set_int = lib.lookup(SetIntFn, "SetInt") orelse std.debug.panic("ARG!", .{});
	
	var i : i32 = 1;
	set_int(&i);
	std.debug.print("i: {}\n", .{i});
}

build.zig:

const std = @import("std");

pub fn build(b: *std.Build) void {

    // Build the DLL
    const lib = b.addSharedLibrary(.{
        .name = "mathlib",
        .root_source_file = b.path("src/lib.zig"),
        .target = b.graph.host
    });

    // Build the executable
    const exe = b.addExecutable(.{
        .name = "main",
        .root_source_file = b.path("src/main.zig"),
        .target = b.graph.host
    });

    // Install both the DLL and the executable
    b.installArtifact(lib);
    b.installArtifact(exe);
}

It builds just fine with no errors or warnings. It runs just fine except it outputs:

i: 1

Why is this not working? What am I missing, for the record, I tried adding link_libc to switch it between ElfDynLib and DlDynLib, both dynamic implementations fails on pure zig dynamic libraries.

1 Like

Change this:

const SetIntFn = *const fn (ptr : *i32) void;

Into this:

const SetIntFn = *const fn (ptr : *i32) callconv(.C) void;

export fn makes the function match the C ABI: Documentation - The Zig Programming Language

5 Likes

Thanks that worked!

It would probably makes sense to have lookup warn you if no calling convention is defined, but Iā€™m not certain Dynamic Libraries are final yet, so letā€™s not trouble the zig developers about that just yet.

There is an open PR for this, but someone needs to de-bitrot it.

1 Like

Well I feel morally obligated to take a look. The PR looks fairly straightforward. Iā€™ll see if I canā€™t find time to give it a spin and find my zig rust cleanerā€¦ Who in their right mind named their programming language rust. Never realized how hilarious that is.