6

古い C ライブラリへの C++ ラッパーを作成する必要があります。

クラスメソッドでは、他のものと一緒に関数ポインターも取るac関数を呼び出す必要があります(これはイベントハンドラーであり、関数はイベントが発生したときに起動される関数を取ります)。

その簡単な例は次のとおりです。

void myclass::add_handler(std::function<void()> handler, otherstuff...)
{
    /*
     *  Many things.
     */

    type_of_function_pointer_accepted_by_old_c_library_add_handler nameofvariable =
    [handler](same_arguments_as_in_definition_of_the_old_c_function_pointer_accepted)
    {
        /*
         *  Many other things with other stuff to be done before the
         *  handler but always only when fired and not when myclass::add_handler is called.
         */
        handler();
    };

    old_c_library_add_handler(nameofvariable);

    /*
     *  Last things.
     */
}

私が知っているように、コンパイラは、ラムダをキャプチャ付きで古い C 関数ポインタに割り当てることができないと文句を言います。問題は、どうすれば解決できますか?

4

1 に答える 1

7

ここに例があります。C++ 標準によれば、何もキャプチャしないラムダは関数ポインタとして使用できるという事実を利用しています。

/* The definition of the C function */
typedef void (*PointerToFunction)();
void old_c_function(PointerToFunction handler, void* context);


/* An example of a C++ function that calls the above C function */
void Foo(std::function<void()> handler)
{
    auto lambda = [] (void* context) {
        auto handler = reinterpret_cast<std::function<void()>*>(context);
        (*handler)();
    };

    old_c_function(&lambda, &handler); 
}

あなたのコンテキストで同じアイデアを使用できると思います。

于 2013-09-12T06:24:49.453 に答える