0

So I've been tinkering around with object orientism in C by making a simple little stack using a 'class' struct and a typedef'd 'instance' struct. The class struct is simply full of function pointers that operate on pointers to instance structs. When I first went about it, I said to myself "I'll just bind the pointers when I initialize the instance struct!" You might guess that this didn't work, since my initialization function was actually a pointer that still had not been assigned a value yet.

(it's currently almost 5AM - closer to wakeup time than bedtime)

So, I am asking if there is any way to effectively bind the function pointers of the at runtime such that I don't need to explicitly call a function that binds them - I was thinking maybe some sort of counterpart to atexit.

Sean Allred
  • 3,558
  • 3
  • 32
  • 71
  • 1
    See if http://stackoverflow.com/q/5222008/365188 OR http://stackoverflow.com/q/4880966/365188 is what you are looking for – Ozair Kafray Jul 20 '12 at 09:02
  • The GCC thing works *great* for me, but it's not portable. The second link you provided is *definitely* not portable XD (from what I can tell) – Sean Allred Jul 20 '12 at 09:21
  • 1
    Who can't you just declare the "class" struct as a static object initialized with the correct function pointers? – dpi Jul 20 '12 at 09:24
  • @vermiculus: look at this answer for a portable solution! Probably the only one – Ozair Kafray Jul 20 '12 at 09:41

1 Answers1

2

If the 'class' struct is always the same, you can initialise it statically:

void do_x_to_instance(instance *);
struct class_type {
    void (*do_x)(instance *);
    ...
} myclass = {
    &do_x_to_instance,
    ...
};

This is how the Python C API works to define extension types, for example.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Would I still be able to do this even if the functions haven't been defined yet? – Sean Allred Jul 21 '12 at 07:58
  • @vermiculus yes, as long as the function has been declared at that point you can take a function pointer to it; the linker will ensure that the function pointer takes the correct value. – ecatmur Jul 22 '12 at 21:17