6

私は最近libffiを使用していますが、C APIを使用しているため、抽象化はvoidポインター(古き良きC)を使用して行われます。このAPIを利用するクラス(可変個引数テンプレートを使用)を作成しています。クラス宣言は次のとおりです。(ここで、Ret=戻り値およびArgs=関数の引数)

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

このクラス内で、2つの異なる関数も宣言されています(簡略化)。

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

Callから使えるようになりたいCallbackBind; それが私の問題です。void*配列をテンプレート化された引数リストに変換する方法がわかりません。これは私が多かれ少なかれ欲しいものです:

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 */);
}

これが達成できない場合、回避策やさまざまな解決策がありますか?

4

1 に答える 1

5

タイプを反復処理するのではなく、パラメーターパックを作成し、可変個引数テンプレートで展開します。配列があるので、必要なパックは、配列インデックスとして機能する整数0、1、2...のパックです。

#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...>());
  }
};

index_tuple.hを使用したそのようなもの

秘訣は、CallbackBindがindex_tuplearg位置を表す整数を作成し、別の関数にディスパッチして整数を推定し、パックをキャスト式のリストに展開して、ラップされた関数の引数として使用することです。

于 2012-06-25T19:45:28.737 に答える