Function Index with Undefined Parameter

I want to have a pointer to a function that can accept various types of parameters. How to do it?

In the following example (line 1), I want void (*fp)(int) be able to take void (*fp)(char*) . The following code does not compile properly, because I pass char * where int is assumed, so compiling the following code will give you warnings (and will not 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 trying to pass an integer 5 as a char * parameter is stupid, but this is not a problem for this question. If you want, you can replace char * with float.

+4
source share
4 answers

I would say use void (*fp)(void*) , then pass pointers to your variables and leave them as void *. This is pretty hacky, but it should work.

eg:

 void callIt(void (*fp)(void*)) { int x = 5; (*fp)((void*)&x); } 
+3
source

What do you expect from calling stringPrint exactly?

It seems that if you do this, it will try to print the contents of memory cell 5 as a string. I suspect that this is not what you want, as it is crashing, and I suspect that you intended to print it "5".

Note that ... at least one named argument is required. Emptying * and abusive cast will at least be compiled.

+1
source

Although this is not the case, the type of function pointer does not matter.

Just define it as

 typedef void (*fp_t)(void * pv); 

The only thing you need to make sure is how you call it that corresponds to the function that you assign 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)); ... 
+1
source

Why don't you make it a pointer to a function that takes the void * parameter?

 void(*fp)(void*) 

This will take care of all possible pointer options. Now for data types you can either create one type of function pointer for each, or only for functions that will be used with function pointers, pass data types as pointers and dereference them at the beginning of the function. This is just an idea, not knowing exactly what you want to do.

0
source

All Articles