Posts Tagged ‘Void *’

Generic Function Pointers In C And Void *

Tuesday, November 25th, 2008

Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email

Many times people ask me about what keyword \ type they should use to declare a generic function pointer in C, or worse still, they don’t ask and steam ahead using “void *”. Well, C does not have a generic function pointer type but it does have a generic function pointer. We’ll see why void * cannot be used to denote generic function pointers and so how we can declare them, but first a brief word on why would someone need a generic function pointer in the first place.

Why do we need Generic Function Pointers?

Well, let’s explain this with the help of a slightly advanced example of a module M1 that supplies information to a lot of other modules M2, M3, M4…Mn. M1 provides this information to modules Mn through callbacks but all these modules need different kind of information and different prototypes for their callback functions. These modules register with M1, using an API, say M1_register(Mn_callback_ptr). Now, either we could have a separate registration API for each “type/class” of subscriber Modules depending on what kind of callback they are giving, or we can have a generic function pointer, to which they typecast their actual callback to and then call the registration API. M1, on the other hand, typecasts this callback pointer to its original form while calling callbacks appropriately.

Why can’t we use void* for a Generic Function Pointer?

This is because a void* is a pointer to a generic “data” type. A void * is used to denote pointers to objects and in some systems, pointers to functions can be larger than pointers to objects. So, if you convert amongst them, you’ll lose information and hence, the situation would be undefined and implementation dependent. Most compilers won’t even warn you if you convert between them but some might error out, if you try to call such a void * to function pointer converted. But even they might fail to alert you, if you take care of typecasting the call perfectly (Enclose in parentheses before function call brackets). And then, one fine day, you’ll try to compile and run your program on one of the aforementioned systems, and then keep on wondering why your program segfaults.

Note: C++ does allow this “conditionally” which means that such a conversion is allowed but a compiler is not bound to implement this feature, which again makes its usage circumspect.

So, how exactly do we declare a Generic Function Pointer?

(more…)

© Safer Code | Generic Function Pointers In C And Void *

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below