For a project I'm working on, it's desirable to have a generic "pointer to a function" type. However, in C, to have a pointer to a function, you need to specify the prototype in the type of the function pointer.
For example, if I have the function void setdata(short data)
, I can't store that in the same pointer as I would a function int getdata()
, because their arguments and return values are different.
After some lateral thinking, I came up with the following workaround:
typedef long (* PFL)(); /* pointer to function that returns a long... */
typedef short (* PFI)(); /* pointer to function that returns a short... */
typedef void (* PFV)(); /* pointer to function that returns a void... */
typedef void (* PFVAL)(long); /* pointer to function that returns a void...
but has a long argument...*/
typedef void (* PFVAI)(short); /* pointer to function that returns a void...
but has an short argument...*/
typedef void (* PFVAU)(unsigned short);
typedef void (* PFVAII)(short, short); /* same as above, but two shorts... */
typedef void (* PFVAUU)(unsigned short, unsigned short); /* same as above, but two shorts... */
typedef union {
PFV pfv;
PFI pfi;
PFL pfl;
PFVAL pfval;
PFVAI pfvai;
PFVAU pfvau;
PFVAII pfvaii;
PFVAUU pfvauu;
} FP;
Sure enough, I'm able to initialize instances of this type like so:
FP funcpointer = { .pfvai = setdata };
Clang and GCC don't complain. Is this a bad idea?
union
is used, I recommend to store yours in a struct along with another field containing the function type. It could be anenum
likeenum {PFV_ID, PFI_ID, PFL_ID, PFVAL_ID, PFVAI_ID, PFVAU_ID, PFVAII_ID, PFVAUU_ID} pfType;
. – Salsifyfuncpointer.pfvai(newdata)
. – Donleyvoid(*)(void)
as your generic pointer to function type, exactly as you would usevoid*
as a generic data pointer type. – Dominicadominical