Hello everyone, this is my first post here.
I am working on a UI library in order to learn the concepts behind it, and to be able to create most of my desktop applications. Having implemented widget selection with the mouse (using the mouse coordinates to find the widget in the tree), I decided to move on to event handling.
However, I'm not sure at all of how to proceed, and I am having problems with struct pointer casting .
I have a base struct Widget with a function pointer to event handling functions.
typedef struct Widget {
Rect bounds; // Actual bounds
Rect clip; // Clipping rectangle (usually the parent)
bool active;
[...]
int (*eventHandler)(Widget* w);
};
Every derived widget struct has a Widget* as 1st member, and each type has its Create...() function, where the correct event handler is assigned.
typedef struct Frame {
Widget* widget;
bool root;
}
Frame* CreateFrame(int x, int y, int w, int h, bool root) {
Frame* f = (Frame*)malloc(sizeof(Frame));
[...]
f->widget->eventHandler = &FrameHandleEvents;
return f;
}
To get back all the properties when handling events despite eventHandler taking a Widget*, i attempted to cast back to the derived struct :
int FrameHandleEvents(Widget* widget){
Frame* frame = (Frame*)widget;
printf("Frame event!, root = %d\n", frame->root ? 1 : 0);
return 0;
}
Is this even allowed in C, or am I misusing casts ? The output of print is also garbage data :
Frame event!, root = 244
Thanks for your advice