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

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

问题描述

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

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?

推荐答案

可变参数的函数使用调用约定,通常是主叫负责从堆栈弹出函数的参数,所以是的,它可以动态地做到这一点。它不是在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 调用约定要求的参数以正确的顺序推,呼叫后,推字节作为参数调用被弹出之前。以这种方式,被调用的函数可以接收的参数的任意数量,作为呼叫者将处理恢复的堆栈指针到它的$ P $对 - 呼叫状态。之前,由参数占用的空间 ... 是字节数安全下界推。附加可变参数是在运行时PTED间$ P $。

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天全站免登陆