将c ++ lambda传递给旧的c函数指针

use*_*602 5 c lambda function-pointers wrapper c++11

我必须为旧的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.
     */
}
Run Code Online (Sandbox Code Playgroud)

据我所知,编译器抱怨我无法将带有捕获的lambda分配给旧的c函数指针.问题是:我该怎么做才能解决?

Ale*_*tof 6

这是一个例子.我们使用的事实是,根据C++标准,不捕获任何内容的lambda可用作函数指针.

/* 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); 
}
Run Code Online (Sandbox Code Playgroud)

我相信你可以在你的上下文中使用相同的想法.