Search code examples
c++typedeffunction-call

Avoid counting array elements in function call


I'm defining a function signature in order to perform a remote procedure call. Due to undefined behavior, I cannot increment the index variable in the call expression so I ended up counting from 0 to the last index and passed each to the function as argument. Is there a more elegant way to accomplish this without counting? I was thinking about a loop or something. This would come in handy when the fixed arguments count changes to e.g. 16 arguments instead of 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]);
}

I know there are variable arguments using va_start, va_list and va_end but I'm not sure if they can be used here.


Solution

  • A part of your solution involves unpacking a fixed amount of values from your arguments array and calling function with it. The following C++14 code will do that:

    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>{});
    }