0

I'm writing some generic functions in Zig, but using Gtk's C api more or less directly (no language bindings). Say I have a widget pointer that I want to cast to a window pointer. How do I determine if the widget in fact is a window?

What I want to do is test whether the widget is also another type of widget before attempting to do the cast. If it's valid, I do the cast and return the pointer. If it isn't valid, I return null.

  • Does this answer your question? [How do I check the type of widget in GTK+3.0?](https://stackoverflow.com/questions/63400120/how-do-i-check-the-type-of-widget-in-gtk3-0) – Joseph Sible-Reinstate Monica Jun 12 '21 at 04:25
  • Well, assume they - the widgets - all have a specific "header" (data prepending), then you can assume that at some fixed point after say n bytes there is an "identifier", like, for example, a string. You see, GTypeInfo here is this identifier, but way more complex than a simple string. You could write a macro yourself to accomplish then what you want, just for the widgets you are using by probing some specific part of the data structure. – muzzletov Jun 12 '21 at 10:56

1 Answers1

0

@Joseph-Sible-Reinstate-Monica pi me on the right path here, although I had to do a bit of extra work because I'm using Zig.

Zig imports C code by translating it to Zig, and unfortunately one of the areas where this can fail is when macros are heavily involved, as is the case here. However, by looking at what the macros actually do I was able to find the functions which return a widget identifier for each given type of widget, and then just match that up with the identifier which is embedded inside the widget data structure. And it's way in there...

ptr.*.parent_instance.g_type_instance.g_class.*.g_type;

In Zig, .* means dereference the pointer, so we deref the widget pointer, get the patent_instance field, then the g_type_instance, g_class, deref that, and finally arrive at the destination. Fun. I'm glad it at least works out to a one-liner. Then match that up with (for a GtkWindow) gtk_window_get_type(). Of course it's slightly more complicated, because in that case I'd also have to check against GtkApplicationWindow and others, but at any rate I found a workable solution.

Thank you all for answering.