参数数目可变的函数的指针

时间:2022-10-25 16:04:46

I have a function with the following prototype:

我有一个函数的原型如下:

void func(int an, ...);

And I would like to store the adress of this function and call it later. I have really no idea to how to do that, I desesperatly tried :

我想存储这个函数的地址,稍后调用它。我真的不知道该怎么做,我试过:

void (*funcPtr)(int, ...);  // Declaration
funcPtr = func;     // Storage
(*funcPtr)(3,2,5);      // Call

This code compiles fine, but at execution it does crap, when I enter my function the arguments in my va_list are not the ones I sent.

这段代码编译得很好,但是在执行过程中它会出错,当我输入函数时,我的va_list中的参数不是我发送的。

Thanks in advance

谢谢提前

EDIT : Alright, I just forgot the first argument. In my code above, the call line should be replaced with:

编辑:好的,我刚刚忘记了第一个参数。在我上面的代码中,调用行应该替换为:

(*funcPtr)(3,3,2,5);        // Call

1 个解决方案

#1


1  

Functions are pointers naturally. So you can simply call:

自然函数指针。所以你可以简单地调用:

funcPtr(3,3,2,5);

It looks like you have everything right. If the function does not have variable arguments, it is a really good idea to declare the function pointer with the right "shape" of arguments for protection from passing malformed arguments.

看起来你一切都很好。如果函数没有变量参数,那么将函数指针声明为具有正确的“形状”参数的函数指针,以防止传递错误的参数,这是一个非常好的主意。

#1


1  

Functions are pointers naturally. So you can simply call:

自然函数指针。所以你可以简单地调用:

funcPtr(3,3,2,5);

It looks like you have everything right. If the function does not have variable arguments, it is a really good idea to declare the function pointer with the right "shape" of arguments for protection from passing malformed arguments.

看起来你一切都很好。如果函数没有变量参数,那么将函数指针声明为具有正确的“形状”参数的函数指针,以防止传递错误的参数,这是一个非常好的主意。