Evan Rempel <erempel@uvic.ca> writes:
I am having difficulties understanding the code that handles the LogQueueFifo objects.
For instance
static void log_queue_fifo_push_head(LogQueue *s, LogMessage *msg, const LogPathOptions *path_options) { LogQueueFifo *self = (LogQueueFifo *) s; LogMessageQueueNode *node;
...
I don't understand how a LogQueue* can be passed in, and then cast to a LogQueueFifo* when the structs are not the same. Then fields in the LogQueueFifo* are referenced but they won't have any meaning because the LogQueue* didn't have the same data at the same location.
I am a little rusty in C, so can someone explain this to me please?
What happens here, is that this function is a callback, which has a generic prototype, but one that will always get a LogQueueFifo passed to it. A LogQueueFifo can also serve as a LogQueue, since its first member *is* a LogQueue struct, so when cast over, it will Just Work. LogQueueFifo is a child object of LogQueue. And due to the way these callbacks work (see log_queue_fifo_new()), we can be sure that a callback like this will always get a LogQueueFifo, therefore, the cast from parent type to child type is safe. Since we passed a pointer, the rest of the LogQueueFifo structure will be there in the memory too, and once we did the cast, they become accessible too. Hope that sheds some light on it. -- |8]