Search code examples
c++linuxc++11g++libffi

Variadic templates: iterate over type/template argument


I've been working with libffi lately, and since it uses a C API, any abstraction is done by using void pointers (good ol' C). I'm creating a class (with variadic templates) which utilizes this API. The class declaration is the following: (where Ret = return value and Args = function arguments)

template <typename Ret, typename... Args>
class Function

Within this class I have two different functions declared as well (simplified):

Ret Call(Args... args); // Calls the wrapped function
void CallbackBind(Ret * ret, void * args[]); // The libffi callback function (it's actually static...)

I want to be able to use Call from CallbackBind; and that is my problem. I have no idea how I am supposed to convert the void* array to the templated argument list. This is what I want more or less:

CallbackBind(Ret * ret, void * args[])
{
 // I want to somehow expand the array of void pointers and convert each
 // one of them to the corresponding template type/argument. The length
 // of the 'void*' vector equals sizeof...(Args) (variadic template argument count)

 // Cast each of one of the pointers to their original type
 *ret = Call(*((typeof(Args[0])*) args[0]), *((typeof(Args[1])*) args[1]), ... /* and so on */);
}

If this is not achievable, are there any workarounds or different solutions available?


Solution

  • You don't want to iterate over the types, you want to create a parameter pack and expand it in a variadic template. You have an array, so the pack you want is a pack of integers 0,1,2... to serve as array indices.

    #include <redi/index_tuple.h>
    
    template<typename Ret, typename... Args>
    struct Function
    {
      Ret (*wrapped_function)(Args...);
    
      template<unsigned... I>
      Ret dispatch(void* args[], redi::index_tuple<I...>)
      {
        return wrapped_function(*static_cast<Args*>(args[I])...);
      }
    
      void CallbackBind(Ret * ret, void * args[])
      {
        *ret = dispatch(args, to_index_tuple<Args...>());
      }
    };
    

    Something like that, using index_tuple.h

    The trick is that CallbackBind creates an index_tuple of integers representing the arg positions, and dispatches to another function which deduces the integers and expands the pack into a list of cast expressions to use as arguments to the wrapped function.