Generating C bindings via Zig's type reflection

I have a project where I need to automatically create some bindings between simple C libraries.
I want to take a header file with some types and functions and generate C code to serialise/deserialise the data needed for the calls.

I looked at SWIG, but it occurs to me that Zig’s type reflection can probably be used to do the hard part.
A quick play with @cImport() and @typeInfo() suggests that I can get all of the info I need from a header.

Before I go down the rabbit hole, are there Zig projects which do things like this which I could start from?

IDK of any projects that do that, but I have a vague Idea of how.

You’d want to use the build systems addTranslateC, instead of @cImport (it’s just translate c under the hood anyway), this lets you dynamically choose which headers your generator is importing so you can have a single generic generator.

Make an exe from the generator and the translated headers, and pass the output location as a CLI arg. This lets you integrate with zigs cache system.

3 Likes

That’s not going to work terribly well, since @typeInfo() doesn’t give you the names of function arguments. You’ll also lose distinction between different int types, as everything will show up as c_int.

That could make the bindings hard to read, but they should still work, no?

Most likely you can do this more easily using JavaScript. There’re decent parser that you can use. You might even be able to rely on just regular expressions to capture the needed info.