避免在函数调用中计算数组元素

Avoid counting array elements in function call

本文关键字:计算 数组元素 函数调用      更新时间:2023-10-16

我正在定义一个函数签名以执行远程过程调用。由于undefined behavior,我无法在调用表达式中递增索引变量,因此我最终从 0 计数到最后一个索引,并将每个索引作为参数传递给函数。有没有更优雅的方法可以在不计数的情况下完成此操作?我在想一个循环什么的。当固定参数计数更改为例如 16参数而不是8.

typedef unsigned long long int functionType(int, int, int, int, int, int, int, int);
unsigned long long int call_address(uintptr_t real_address, const unsigned int *arguments) {
    auto function = (functionType *) real_address;
    // We count instead of incrementing an index variable because: operation on 'argumentIndex' may be undefined
    return function(arguments[0], arguments[1],
                    arguments[2], arguments[3],
                    arguments[4], arguments[5],
                    arguments[6], arguments[7]);
}

我知道有使用 va_startva_listva_end 的变量参数,但我不确定它们是否可以在这里使用。

解决方案的一部分涉及从arguments数组中解压缩固定数量的值并使用它调用function。以下 C++14 代码将执行此操作:

template <typename F, size_t... Is>
unsigned long long int our_invoke(F f, const unsigned int * args, std::index_sequence<Is...>) {
    return f(args[Is]...);
}
unsigned long long int call_address(uintptr_t real_address, const unsigned int *arguments) {
    auto function = (functionType *) real_address;
    return our_invoke(function, arguments, std::make_index_sequence<8>{});
}