The Zig-implementation lives in
youtube-tutorial
.
Zig has the capability to translate C code to Zig code using a CLI tool via zig translate-c
or in code with the built-in function @cImport()
.
Unfortunately Zig isn't capable of translating complex C code that heavily relies on macros like GTK4. Because of this, we aren't able to create custom widgets in a simple fashion.
The compromise I'm using is to create the boilerplate code in C while implementing the "heavy-lifting" methods in Zig.
Zig data types carry extra information (like alignment) compared to C so it isn't trivial to use C pointer types directly in Zig. A lot of explicit casting has to take place, which in fairness happens in C as well, but the GTK4 macros masks out most of this noise.
That said, the idea is to convert as much C code to Zig while retaining sanity:
-
youtube-tutorial/1
. The custom method (if we stick with the OOP metaphor) implementations are moved todemowidget.zig
. These are all under an opaque type calledDemoWidget
exposing a canonical Zig function-calling scheme.demo_widget_init()
.demo_widget_dispose()
.demo_widget_finalize()
.demo_widget_class_init()
.- A public "ziggified" version of
demo_widget_new()
toDemoWidget.new()
. - Helper "ziggified" functions for internal use:
DemoWidget.get_parent_class()
,DemoWidget.get_button()
,DemoWidget.set_button()
. These are required becauseDemoWidget
is an opaque type, and we can't access fields directly. The setter/getter implementation is on the C side indemowidget.c
.
-
youtube-tutorial/2
-
youtube-tutorial/3
-
youtube-tutorial/4
. At this point I determined that there is wayyyyyy too much hassle dealing with explicit casts that need to happen on almost every line of code so using GTK4 viatranslate-c
is impractical. We should wait for some awesome people to create actual Zig bindings. -
youtube-tutorial/5
-
youtube-tutorial/6
Although I learned a lot about Zig during this experiment I would not advise anyone to interoperate with C via translate-c
directly when dealing with complex libraries like GTK4.
The only practical application for translate-c
is for libraries that generate bindings really, anything more get too complex because of explicit casting needed at almost every line.
I'm keeping this repo around as a showcase.
Go into any youtube-tutorial/*
subfolder and execute zig build run
to build and run the app.
libgtk-4-dev
This work is not possible without the GTK4 tutorial by Logan Rathbone and atoft's Reactions GIF search app that put me on the right track to understanding how to interoperate with GTK4 in C.