c - 使用 n 个参数运行函数

标签 c function undefined

我需要用原始 ANSI C (1989) 解决一个问题。

我有一些指针 (void *func) 可以使用 (int n) double 参数运行,并且有数组 double values[]n 数字。所以我想用位于值中的 n 参数运行我的函数。

例如我有函数:

double hypotenuse(double x, double y, double z);

所以

void *func = (void *)hypotenuse; double values[3] = {5, 4, 3}; int n = 3;

我想做这样的事情:

func(n, values);

问题是我不能改变函数的原型(prototype), 所以我需要以某种方式执行此操作(也许是一些宏?)。

最佳答案

主要问题是您必须根据参数的数量(即根据 n 变量)以不同方式转换指针。

一种方法是使用包含参数编号的 switch 语句的包装函数:

double wrapper(void *func, double args[], int n)
{
    switch (n)
    {
    case 0:
        return ((double (*)(void)) func)();
    case 1:
        return ((double (*)(double)) func)(args[0]);
    case 2:
        return ((double (*)(double, double)) func)(args[0], args[1]);
    case 3:
        return ((double (*)(double, double, double)) func)(args[0], args[1], args[2]);
    default:
        printf("Error: wrapper called with %d arguments\n", n)
        break;
    }

    return 0.0;
}

关于c - 使用 n 个参数运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14889917/

相关文章:

function - GHC API : Find all functions (and their types) in scope

Javascript:找出数组中是否至少有两个不同的值

Python:函数中调用的尚 undefined variable - 但有效吗?

c++ - 如何从 uint8_t 数组中提取不同大小的值?

c++ - 将 DBF 转换为 JSON

function - Mathematica 中的递归函数

haskell - Haskell 的类型系统是否同构于一个不一致的逻辑系统?如果是这样,后果是什么?

c - 为什么 realloc 每次都失败?

c - 如何对结构数组中的字符串进行冒泡排序

php - 使用 GET 和 POST 在 PHP 中 undefined index