Zig C Integration Note
Meow King
1 min read
C function take a function as parameter
Take stb
image library as example:
int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes);
int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data);
int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data);
int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality);
where the callback is:
void stbi_write_func(void *context, void *data, int size);
Corresponding Zig function.
fn stbWriteCallback(context: ?*anyopaque, data: ?*anyopaque, size: c_int) callconv(.C) void {
const array_list: *std.ArrayList(u8) = @ptrCast(@alignCast(context.?));
const bytes: [*]const u8 = @ptrCast(data.?);
const bytes_slice: []const u8 = bytes[0..@as(usize, @intCast(size))];
array_list.appendSlice(bytes_slice) catch unreachable;
}
0
Subscribe to my newsletter
Read articles from Meow King directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by