What is the current state of the art for writing bindings to a C library written using gobject? Creating a foo-sys crate using rust-bindgen is not too much hassle, but I'm wondering if there is a similar tool to help write the corresponding foo crate that exposes a safe idiomatic rust interface. A brief email with the gtk-rs devs indicates that the gtk/glib/etc crates have so far been written by hand. It should be possible to automate much of the work though, right?
You are kindly welcome to GObject Introspection bindings for Rust ยท GitHub
I wrote down a summary of the state of affairs for the Rust BoF at GUADEC last month, and it's still pretty much accurate.
Right now I'm making progress on the code generator for -sys crates as part of gi-rust. The gtk-rs team has already done a similar tool, and commendably they did it in Rust (I'm writing mine in Python to reuse the gobject-introspection modules).
My ultimate intent with gi-rust is to be able to generate idiomatic high-level bindings from GIR with some necessary tweaks, but that is a much loftier goal with significant hurdles.
On a somewhat related note: the lack of support for unions in FFI is a big stumbling block in this kind of automatic binding generation. The type mapping code has to determine the largest and the highest aligned union variant (if these are not the same variant, you are SOL) and take that variant to represent the union in the FFI. Repeat for any target OS/architecture where the outcome might be different, and generate a conditional compilation matrix to cope. I wish the organic support for C unions was given more priority.
Indeed, rgtk, the Gtk-rs predecessor, was made entirely by hand. There've been some progress automating things since then. Ignoring minor snags, we're now capable of generating a complete sys crate (see the caveat about unions above, we just ignore them and bit fields in structs for now), the autogenerated crates from this repo have replaced the handmade ones on crates.io. Adding webkitgtk-sys
while not zero effort, would be pretty easy.
The higher level bindings automation is under development, the generator can generate GObject
descendants bindings pretty well but there's more work to do. Some things will need to be handled manually in the foreseeable future. Also, some higher level design decisions (e.g. the balance between static and dynamic treatment of GError
) are yet to be made.
On a better thought, it's enough to calculate the union's total size and alignment per the target ABI, and generate a struct filled with dummy fields so as to have the same size and alignment.
This, however, remains a hassle: