将参数动态传递给可变函数 [英] Passing parameters dynamically to variadic functions

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

问题描述

我想知道是否有任何方法将参数动态地传递给可变参数。即如果我有一个函数

I was wondering if there was any way to pass parameters dynamically to variadic functions. i.e. If I have a function

int some_function (int a, int b, ...){/*blah*/}

我接受来自用户的一堆值,我想要一些将这些值传递给功能:

and I am accepting a bunch of values from the user, I want some way of passing those values into the function:

some_function (a,b, val1,val2,...,valn)

我不想编写所有这些功能的不同版本,但我怀疑没有其他选项?

I don't want to write different versions of all these functions, but I suspect there is no other option?

推荐答案

Variadic函数使用调用约定,其中调用者负责从堆栈中弹出函数参数,所以是的,可以动态地执行。它在C中没有标准化,通常需要一些装配来手动推送所需的参数,并正确地调用可变参数。

Variadic functions use a calling convention where the caller is responsible for popping the function parameters from the stack, so yes, it is possible to do this dynamically. It's not standardized in C, and normally would require some assembly to manually push the desired parameters, and invoke the variadic function correctly.

cdecl 调用约定要求以正确的顺序推送参数,并且在调用之后,在弹出调用之前作为参数推送的字节。以这种方式,被叫函数可以接收任意数量的参数,因为调用者将处理将栈指针还原到其预调用状态。 ... 之前的参数占用的空间是推送字节数的安全下限。额外的可变参数在运行时解释。

The cdecl calling convention requires that the arguments be pushed in the correct order, and after the call, the bytes pushed as arguments before the call are popped. In this way, the called function can receive an arbitrary number of parameters, as the caller will handle reverting the stack pointer to it's pre-call state. The space occupied by the arguments before the ... is the safe lower bound for number of bytes pushed. Additional variadic arguments are interpreted at runtime.

FFCALL 是一个库,它提供了将参数动态地传递给可变函数的包装器。您感兴趣的一组功能是 avcall 。以下是一个调用上述功能的示例:

FFCALL is a library which provides wrappers for passing parameters dynamically to variadic functions. The group of functions you're interested in is avcall. Here's an example calling the functions you gave above:

#include <avcall.h>

av_alist argList;
int retVal;
av_start_int(argList, some_function, retval);
av_int(argList, a);
av_int(argList, b);
av_type(argList, val1);
...
av_type(argList, valn);
av_call(argList);

您还可以找到这个链接讨论围绕C中的可变函数生成包装,以便为了证明这不属于标准C的一部分而感兴趣。

You might also find this link discussing generating wrappers around variadic functions in C, to be of interest in justifying why this isn't part of standard C.

这篇关于将参数动态传递给可变函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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