我有一些我希望根据一些输入调用的函数。每个函数都有不同数量的参数。换句话说,
if (strcmp(str, "funcA") == 0) funcA(a, b, c);
else if (strcmp(str, "funcB") == 0) funcB(d);
else if (strcmp(str, "funcC") == 0) funcC(f, g);
这有点笨重且难以维护。理想情况下,这些是可变参数函数(例如 printf 样式)并且可以使用可变参数。但他们不是。因此,利用 cdecl 调用约定,我通过一个充满参数的结构填充堆栈。我想知道是否有更好的方法来做到这一点。请注意,这仅限于内部(例如,简单工具、单元测试等),不会用于任何可能受到恶意攻击的生产代码。
例子:
#include <stdio.h>
typedef struct __params
{
unsigned char* a;
unsigned char* b;
unsigned char* c;
} params;
int funcA(int a, int b)
{
printf("a = %d, b = %d\n", a, b);
return a;
}
int funcB(int a, int b, const char* c)
{
printf("a = %d, b = %d, c = %s\n", a, b, c);
return b;
}
int funcC(int* a)
{
printf("a = %d\n", *a);
*a *= 2;
return 0;
}
typedef int (*f)(params);
int main(int argc, char**argv)
{
int val;
int tmp;
params myParams;
f myFuncA = (f)funcA;
f myFuncB = (f)funcB;
f myFuncC = (f)funcC;
myParams.a = (unsigned char*)100;
myParams.b = (unsigned char*)200;
val = myFuncA(myParams);
printf("val = %d\n", val);
myParams.c = (unsigned char*)"This is a test";
val = myFuncB(myParams);
printf("val = %d\n", val);
tmp = 300;
myParams.a = (unsigned char*)&tmp;
val = myFuncC(myParams);
printf("a = %d, val = %d\n", tmp, val);
return 0;
}
输出:
gcc -o func func.c
./func
a = 100, b = 200
val = 100
a = 100, b = 200, c = This is a test
val = 200
a = 300
a = 600, val = 0