Function pointer with undetermined parameter

余生颓废 提交于 2019-12-05 17:58:23

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!