Pass a c++ lambda to old c function pointer

喜你入骨 提交于 2019-12-07 06:59:55

问题


I have to create a c++ wrapper to a old c library.

In a class method I must call a c function that takes with other stuff also a function pointer(it is a event handler and the function takes a function that is fired when a event happens).

A simple example of it is this:

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.
     */
}

The compiler complains, as I know, that I can't assign a lambda with capture to an old c function pointer. The question is: how can I do to solve?


回答1:


Here is an example. We are using the fact that lambdas that do not capture anything are, according to the C++ standard, usable as function pointers.

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

I believe you can use the same idea in your context.



来源:https://stackoverflow.com/questions/18746048/pass-a-c-lambda-to-old-c-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!