For example here’s a function in C.
void foo(void *arg) { ... }
I want to pass a number to the function like this
foo((void *)(37));
How do I do it in zig? This is that function when translated to zig
fn foo(arg: ?*anyopaque) void { ... }
For example here’s a function in C.
void foo(void *arg) { ... }
I want to pass a number to the function like this
foo((void *)(37));
How do I do it in zig? This is that function when translated to zig
fn foo(arg: ?*anyopaque) void { ... }
For runtime, start with @ptrFromInt
and then go from there: Documentation - The Zig Programming Language
This works:
src/main.c
#include <stdio.h>
void foo(void* arg) {
int* int_ptr = (int*)arg;
printf("%d\n", *int_ptr);
}
src/main.zig
extern fn foo(arg: ?*const i32) void;
pub fn main() !void {
const n: i32 = 42;
foo(&n);
}
In build.zig
exe.addCSourceFiles(.{
.files = &.{"src/main.c"},
});
Edit: And this too:
foo(&42);
Edit 2: And this:
extern fn foo(arg: *const i32) void;
From what I’ve experienced in this type of C interop, you can really be strict with your types on the Zig side and the compiler will make it work.