There is a library (that comes with a header.h) that runs fine with the c example, but segfaults in zig.
The C Code:
#include <string.h>
#include "irohnet.h"
int main() {
Endpoint_t * ep = endpoint_default();
endpoint_free(ep); // does not segfault
return 0;
}
the zig code (snippet):
const std = @import("std");
const iroh = @import("iroh");
const dprint = std.debug.print;
const DISCOVERY_CONFIG_ALL: c_int = 3;
pub fn main(init: std.process.Init) !void {
const path = "D:\\Code\\Zig\\SystemExamples\\iroh_p2p_dynamic_linking";
var irohny = iroh{
.lib = try .init(init.gpa, path, "iroh_c_ffi"), // dynamic lib because duplicate symbols otherwise
};
defer irohny.lib.close();
const endpoint: ?*iroh.Endpoint_t = irohny.endpoint_default();
irohny.endpoint_free(endpoint); //segfaults here
}
Due to duplicate symbols being a problem I opted to link the dynamic library instead of dealing with that headache. The type definitions and such did come from the translate-c of the header file. iroh.Endpoint_t is defined as an opaque type. As that appears to be the largest
Also (informed by print debugging) irohny.endpoint_default() does not crash and so I believe that the dynamic library is being filled correctly.
In case I am wrong the functions are filled in this manner :
var lib = try load_lib.open(alloc, path, lib_name);
errdefer lib.close();
return .{
.endpoint_bind = lib.lookup(*const fn ([*c]const EndpointConfig_t, ?*SocketAddrV4_t, ?*SocketAddrV6_t, [*c]const ?*Endpoint_t) EndpointResult_t, "endpoint_bind") orelse return error.FunctionNotFound,
.endpoint_free = lib.lookup(*const fn (?*Endpoint_t) void, "endpoint_free") orelse return error.FunctionNotFound,
// and other functions too
};
the lookup function resolves to:
pub fn lookup(self: *Self, T: type, name: [:0]const u8) ?T {
return switch (os) {
// this is run on windows
.windows => @ptrCast(GetProcAddress(self.lib, name.ptr) orelse return null),
else => self.lib.lookup(T, name),
};
}
The library was (before being compiled to a static/dynamic library) written in rust. Any help or advice would be appreciated.