How do I declare a function pointer that can safely point to any function?
I need something like void
pointers, but for functions. I thought about simply using that but, according to the answers to this question, function pointers cannot be reliably converted to data pointers, at least on non-POSIX systems.
I searched and found some possible examples of this:
Windows has FARPROC:
int (FAR WINAPI * FARPROC) ()
The documentation also mentions this:
In C, the FARPROC declaration indicates a callback function that has an unspecified parameter list.
Sounds fine, but what about the return value? It is clearly specified as
int
.One of OpenGL's specifications has:
typedef void (*GLfunction)(); extern GLfunction glXGetProcAddressARB(const GLubyte *procName);
The parameter list is also unspecified, but the return type is clearly specified as
void
.
I'm not sure how to interpret this. The function pointer will be cast to a function pointer type with the appropriate prototype before it is used. For example:
typedef void (*function_pointer_t)();
extern function_pointer_t get_function(const char * name);
/* Somewhere else... */
typedef double (*cosine_function_t)(double);
cosine_function_t cosine = (cosine_function_t) get_function("cos");
Is this code safe? Does it violate any C standard or result in any undefined behavior?