未确定paramater函数指针 [英] Function pointer with undetermined paramater
问题描述
我想有一个函数指针,可以采取多种类型的参数。我该怎么做呢?
I want to have a function pointer that can take various types of parameters. How do I do that?
下面的例子(1号线),我想无效(* FP)(INT)
来能够采取无效(* FP) (字符*)
为好。下面code不正确编译,因为我传递的char *其中int有望使编译如下code会给你警告(并且将无法正常工作)。
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;
}
注:我知道,试图通过整数5为char *参数是愚蠢的,但是这不是对这个问题的关注。如果你愿意,你可以替换的char *使用float。
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.
推荐答案
我想说的使用无效(* FP)(无效*)
,然后在三分球传给你变量和扮演他们为void *。这是pretty哈克,但它应该工作。
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.
例如:
void callIt(void (*fp)(void*))
{
int x = 5;
(*fp)((void*)&x);
}
这篇关于未确定paramater函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!