I have case when I have to create wrapper for C library. For purpose of this post I extracted bare minimum to show that compilation fail but without any specyfic detail:
C .h file
struct lfs_config {
void *context;
int block_cycles;
int (*read)(const struct lfs_config *c, int block,
int off, void *buffer, int size);
};
main.zig:
const std = @import("std");
const c = @cImport({
@cInclude("test.h");
});
pub const lfs_config = struct {
const Self = @This();
read: fn (block: u32, off: u32, buffer: []u8) i32,
pub fn to_lfs_config(self: *const Self) c.lfs_config {
return c.lfs_config {
.context = @ptrCast(@constCast(self)),
.read = lfs_read,
};
}
};
fn lfs_read(config: [*c]const c.lfs_config, block: u32, off: u32, buffer: ?*anyopaque, size: u32) callconv(.C) c_int {
return @as(*lfs_config, @ptrCast(config.*.context)).read(block, off, @as([*]u8, @ptrCast(buffer))[0..size]);
}
pub fn main() !void {
const test_cfg = lfs_config{
.read = zig_test_read,
};
_ = test_cfg.to_lfs_config();
}
fn zig_test_read(block: u32, off: u32, buffer: []u8) i32 {
std.log.info("read: block: {} off: {} size: {}", .{block, off, buffer.len});
return 0;
}
and build.zig:
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "zig-bug",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
exe.addIncludePath(b.path("src"));
b.installArtifact(exe);
}
And compilation error:
PS D:\zig-bug> zig build -Doptimize=Debug
install
ββ install zig-bug
ββ zig build-exe zig-bug Debug native failure
error: the following command exited with error code 5:
C:\Users\arek\AppData\Local\Microsoft\WinGet\Packages\zig.zig_Microsoft.Winget.Source_8wekyb3d8bbwe\zig-windows-x86_64-0.13.0\zig.exe build-exe -ODebug -I D:\zig-bug\src -Mroot=D:\zig-bug\src\main.zig --cache-dir D:\zig-bug\.zig-cache --global-cache-dir C:\Users\arek\AppData\Local\zig --name zig-bug --listen=-
Build Summary: 0/3 steps succeeded; 1 failed (disable with --summary none)
install transitive failure
ββ install zig-bug transitive failure
ββ zig build-exe zig-bug Debug native failure
error: the following build command failed with exit code 1:
D:\zig-bug\.zig-cache\o\6364e598a586d17a6cee190a6f37085e\build.exe C:\Users\arek\AppData\Local\Microsoft\WinGet\Packages\zig.zig_Microsoft.Winget.Source_8wekyb3d8bbwe\zig-windows-x86_64-0.13.0\zig.exe D:\zig-bug D:\zig-bug\.zig-cache C:\Users\arek\AppData\Local\zig --seed 0x8f55c59d -Z121fe3821b95bb50 -Doptimize=Debug
From my initial investigation I am sure that this bug is caused by line:
return @as(*lfs_config, @ptrCast(config.*.context)).read(block, off, @as([*]u8, @ptrCast(buffer))[0..size]);
Any ideas what is wrong here and why zig donβt show any meaningful errors?