是指向具有未知数量的参数的函数的指针可能吗? [英] Is a pointer to a function which have unknown number of parameters possible?

查看:106
本文介绍了是指向具有未知数量的参数的函数的指针可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个简单的类来测量函数的时间性能。用户应该能够发送指针到他的函数,函数的参数,调用函数的次数,我将调用函数,返回经过的时间。这里我的问题是我不知道用户的功能需要多少参数!我想使用可变函数获取未知数量的参数,但是我仍然有一个问题:声明用户作为参数传递的函数指针(因为它没有常量变量数),并且不知道通过使用的变量类型一个可变的函数。

I am writing a simple class to measure performance of a function in terms of time . The user should be able to send a pointer to his function, parameters of the function, times to call the function and i will call the function, return the time elapsed. Here my problem is I dont know how many parameters the user's function takes! I thought to use variadic functions to get unknown number of parameters, however I still have the problem of declaring the function pointer that user passes as a parameter(because it doesnt have constant variable number) and not knowing the types of variables I recieve by using a variadic function.

它不应该难,我猜:)所有我想做的是调用一个函数,它不是由我定义的,通过使用一个函数指针。

It should not be hard, i guess :) All i want to do is to call a function which is not defined by me by using a function pointer.

有没有办法解决这些问题?

Is there any way to solve these problems or?

推荐答案

具有未知参数的函数的函数指针是没有意义的。如果你不知道有多少参数(更不用说它们的类型),你如何在运行时填写参数?

It doesn't really make sense to have a function-pointer to a function with unknown arguments. If you don't know how many arguments there are (let alone their types), how are you going to fill out the arguments at run-time?

最好的可以做的是要求用户的函数都具有相同的原型,即以 va_list 作为参数,并要求您的库为您的库提供相同的 va_list (另请参见 http://c-faq.com /varargs/handoff.html )。

The best you can do is require that the user's functions all have the same prototype, namely to take a va_list as a parameter, and require that your library provide your library with that same va_list (see also http://c-faq.com/varargs/handoff.html).

例如:

// Function-pointer type
typedef void (*func_t)(int, va_list);

// Your timer library function
void timer(func_t *p_func, ...)
{   
    va_list arg;
    va_start(arg, fmt);
    p_func(0, arg);
    va_end(arg);
}


// User's function
void user_function(int first_arg, va_list args)
{
   ...
};

// Invoke the timer library function
timer(&user_function, arg1, arg2, arg3);

这篇关于是指向具有未知数量的参数的函数的指针可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆