If you carefully studied the documentation for this library, you will find that
void some_c_handler(void(*func)(void*), void* data);
Calls func , passing it the data argument.
This is a very common design pattern for C libraries that perform a callback function. In addition to the callback function, they also accept an additional opaque pointer, which is not interpreted by the library but blindly passed to func . In other words, the C library calls
func(data);
You can use this from C ++ code to pass a regular pointer to any class.
This also includes std::function .
The trick is that in most situations you need to use new :
auto *pointer=new std::function< function_type >...
The end result is a pointer that can be passed to the C library along with a pointer to the trampoline function:
some_c_handler(&cpp_trampoline, reinterpret_cast<void *>(pointer));
And the trampoline converts an opaque pointer:
void cpp_trampoline(void *pointer) { auto real_pointer=reinterpret_cast<std::function< ... >*>(pointer);
The only detail you will need to set aside here is to figure out the correct area for the dynamically assigned function pointer to avoid memory leaks.
source share