I want to have a function pointer that can take various types of parameters. How do I do that?
The following example (line 1), I want void (*fp)(int)
to be able to take void (*fp)(char*)
as well. The following code does not properly compile because I'm passing char* where int is expected so compiling the following code will give you warnings (and won't work properly).
void callIt(void (*fp)(int))
{
(*fp)(5);
}
void intPrint(int x)
{
printf("%d\n", x);
}
void stringPrint(char *s)
{
printf("%s\n", s);
}
int main()
{
void (*fp1)(int) = intPrint;
callIt(fp1);
void (*fp2)(char*) = stringPrint;
callIt(fp2);
return 0;
}
Note: I know that attempting to pass integer 5 as char* parameter is stupid, but that's not the concern for this question. If you want, you can replace char* with float.
I would say use void (*fp)(void*)
, then pass in pointers to your variables and cast them as void*. It's pretty hacky, but it should work.
eg:
void callIt(void (*fp)(void*))
{
int x = 5;
(*fp)((void*)&x);
}
What do you expect the call to stringPrint to do exactly?
It looks as though if you do get this working, it's going to end up attempting to print the contents of memory location 5 as a string. Which I suspect is not what you want as it will crash and I suspect you were intending it to output '5'.
Note also that ... requires at least one named argument. Passing a void * and an abusive amount of casting will at least compile.
Although not nice, the type of the function pointer does not really matter.
Just define it as
typedef void (*fp_t)(void * pv);
The only thing you have to make sure is that the way you call it matches the function you assigend to it.
int intFuncWithTwoDoubles(double d1, double d2);
char * pCharFuncWithIntAndPointer(int i, void * pv);
...
fp_t fp = NULL;
fp = intFuncWithTwoDoubles;
printf("%d", fp(0.0, 1.0));
fp = pCharFuncWithIntAndPointer;
printf("%s", fp(1, NULL));
...
Why don't you make it a function pointer that accepts a void* parameter?
void(*fp)(void*)
This would take care of all possible pointer parameters. Now for data types you could either make one function pointer type for each or just for the functions that are going to be utilized with the function pointers, pass the data types as pointers and dereference them in the function's beginning. That's just an idea without knowing exactly what you want to do.