Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a c++ lambda to old c function pointer

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?

like image 940
user2714602 Avatar asked Sep 11 '13 16:09

user2714602


1 Answers

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.

like image 115
Alex Shtof Avatar answered Oct 09 '22 11:10

Alex Shtof