I've been trying to figure out a way to change a type of function registered with a C-callback, to conform with an interface I am implementing.
C-callback (external lib, can't be changed):
typedef void* handle_t;
register_callback(void(*callback)(handle_t handle));
My class:
MyClass::MyClass(std::function<void()> callback) { // <- interface forces this parameter
register_callback(callback);// <- this is the idea.
}
I want user to provide void(void) function and register it with this callback.
Reason: standardized implementation of an interface. Interface defines "std::function<void()>
" parameter, so I can't use void(void*) as a parameter. This is ok, because that handle_t parameter in callback is completely useless, as a user has access to this handle via my wrapper class.
Obviously I can't register void(void)
with void(void*)
callback, so I need some sort of a wrapper. The problem is, I can't create this wrapper as a member function inside my class, as they can't be passed to a C-callback.
I've been playing with an idea of using lambdas like this:
MyClass::MyClass(std::function<void()> callback) : callback_(std::move(callback)) {
std::function<void(handle_t)> callback_wrapper = [&](handle_t) { callback_(); };
register_callback(callback);
}
But this lambda probably won't work, because it is created inside constructor and will be freed on exit. Ideally I would have it inlined, so the lambda itself isn't called, but it is replaced with my desired callback function.
Will gladly accept any guidance on how to tackle this problem.