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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With