Last active
January 26, 2025 15:00
-
-
Save cfillion/420d9ac7ac2f8810517834a82cf00afe to your computer and use it in GitHub Desktop.
Type alias for Zig bindings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn Alias(a: type, b: type) type { | |
return struct { | |
fn fixType(t: anytype) void { | |
var info = @typeInfo(t.*); | |
switch(info) { | |
.Pointer => |*ptr| { | |
if(ptr.child == a) { | |
ptr.child = b; | |
ptr.alignment = @alignOf(a); | |
} | |
}, | |
else => {}, | |
} | |
t.* = @Type(info); | |
} | |
fn FuncType(fptr: anytype) type { | |
var ptr_type = @typeInfo(@TypeOf(fptr)); | |
var child_type = @typeInfo(ptr_type.Pointer.child); | |
var fn_type = &child_type.Fn; | |
fixType(&fn_type.return_type.?); | |
var params: [fn_type.params.len]std.builtin.Type.Fn.Param = undefined; | |
@memcpy(¶ms, fn_type.params); | |
for(params[0..]) |*param| | |
fixType(¶m.type.?); | |
fn_type.params = params[0..]; | |
ptr_type.Pointer.child = @Type(child_type); | |
return @Type(ptr_type); | |
} | |
pub fn cast(func: anytype) FuncType(&func) { | |
return @ptrCast(&func); | |
} | |
}; | |
} | |
// Usage | |
pub const Foo = struct { | |
const alias = Alias(c.foo_t, Foo); | |
pub const init = alias.cast(c.foo_init); | |
pub const func = alias.cast(c.foo_func); | |
}; | |
var foo = Foo.init(); | |
// foo.func() impossible as of Zig 0.13 because of https://github.com/ziglang/zig/issues/18233 | |
Foo.func(foo); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment