Search code examples
cgtkgobject

How can I make a class that can inherit from any type of GTK+ 2.0 widget in C?


How can I make a class that can inherit from any type of GTK+ 2.0 widget in C? I know if I were to use C++ I would have a template that inherits from it's parameter and adds the behavior that I need, and that if I were to do something similar with Objective-C I might use NSProxy and forward messages to a class member which is the real view controller, but I have no idea how I'd accomplish the same task in C with GTK+ 2.0.

How can I make a class that can inherit from any type of GTK+ 2.0 widget in C?

P.S. Some are going to ask why. Asking why is fair enough. As you can see by my previous question What GUI libraries are not object-oriented? I have been challenging myself to program in a non object-oriented way. Because I want to program in a non object-oriented way, I need to abstract over all the classes available in GTK+ 2.0 to present the kind of behaviour I want. Specifically, I need to make each class work with continuations.

A simple continuation implementation is:

struct CONTINUATION;
typedef struct CONTINUATION continuation;
struct CONTINUATION {
     void* environment;
     continuation (*ip)(void*); 
};

A class which wants to send a message to it's continuation would continuously replace it's continuation with the results of it's ip applied to it's environment until the ip value points to the (stub) function event_get. Then, the class would use the information in environment to respond appropriately, and to get a new continuation, so the cycle can start all over again for the next message.


Solution

  • It's pretty easy; whenever you want to inherit from a type use g_type_register_dynamic and supply the parent type. I'm not clear why you'd want to subclass existing types, though; it'd seem easier in most cases to just attach your own information using g_object_set_qdata_full and use existing signals to connect your continuations.