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?
static myclass::some_function
and copy it to the c function pointer instead of the lambda. Then inside the static function how can I retrieve the capture variables I take in the lambda? Can you please write a bit of example code? – Rold_c_library_add_handler
really look like? Reasonably designed C libraries often allow one to pass avoid*
pointer or similar, together with the callback. When they call the callback, they pass that pointer right back to it, for context. See if your library is one of those. If not, then I'm afraid you will have to resort to non-portable hacks, like creating machine code thunks on the fly. – Hauckold_c_library_add_handler
takes a void* argument that is the blob that contains something the handler can take from the caller. I don't know how to transform astd::function<void()> handler
to avoid*
parameter and then, inside the handler, transform it again to astd::function<void()> handler
so I can call it. – R