传递函数的参数不确定数量和可变参数调用它 [英] Pass a function with undetermined number of arguments and call it with the variadic arguments

查看:229
本文介绍了传递函数的参数不确定数量和可变参数调用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个接受与参数作为参数数目不详的函数的函数偷懒。我需要什么类型或强制转换做?

I'd like to create a function "lazy" which accepts a function with an undetermined number of arguments as parameter. What type do I need or which casts have to be done?

然后我想执行后面的功能评估说事儿。我怎么那么前通过我传递的参数给懒人功能来传递函数指针?

Then I want to execute that thing later in function "evaluate". How do I then pass the arguments I passed before to the "lazy" function to the passed function pointer?

有些code来说明我的问题:

Some code to illustrate my problem:

char *function_I_want_to_call(void *foo, type bar, ...);
// the arguments are unknown to lazy() and evaluate()

typedef struct {
    ??? func;
    va_list args;
} lazy_fcall;

void lazy(lazy_fcall *result, ??? func, ...) {
// which type do I need here?
    va_start(result->_args, fund);
    result->func = func;
}

void *evaluate(lazy_fcall *to_evaluate) {
    return to_evaluate->func(expand_args(to_evaluate->args));
    // what do I have to write there to expand the va_list? It's C, not C++11...
}

int main () {
    lazy_fcall lazy_store;
    lazy(&lazy_store, function_I_want_to_call, "argument_1", "argument_2");
    // ...
    printf("%s", (char *)evaluate(&lazy_store));
}

或者是这样的只是不可能的?其中其他的可能性存在吗?

Or is something like this just impossible? Which other possibilities exist?

推荐答案

您不能展开的va_list 成单独的参数。要调用函数必须能够采取的va_list 作为参数。例如参见的printf vprintf

You can't expand a va_list into separate arguments. The function you want to call have to be able to take a va_list as argument. See e.g. printf versus vprintf.

另外,由CAF所指出的,你不能存储的va_list ,作为论据指出由它不会是有效的,一旦函数返回。尝试使用的va_list 将导致不确定的行为和各种古怪的。

Also, as noted by caf, you can't store a va_list, as the arguments "pointed" to by it will not be valid once the lazy function returns. Attempting to use the va_list will lead to undefined behavior and all kinds of weirdness.

这篇关于传递函数的参数不确定数量和可变参数调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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