Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Use a recast function pointer in a lambda trampoline to allow arbitrary callback signatures
// Hypothetical asynchronous C library call
typedef void (*future_cb)(void* data);
void call_in_the_future(future_cb cb, void* data) {
template <class C>
struct Base {
template <typename DataType = void*>
void run(void (*cb)(C*, DataType*) = nullptr, DataType* ptr = nullptr) {
auto lcb = [](void* userdata) {
C* wrap = static_cast<C*>(userdata);
auto* cb = reinterpret_cast<void(*)(C*, DataType*)>(wrap->cb_);
DataType* other = static_cast<DataType*>(wrap->ptr_);
if (cb != nullptr)
cb(wrap, other);
cb_ = reinterpret_cast<void(*)()>(cb);
ptr_ = ptr;
// Call the hypothetical asynchronous C library function.
call_in_the_future(lcb, this);
void (*cb_)() = nullptr;
void* ptr_ = nullptr;
class Mine: public Base<Mine> { };
void my_cb(Mine* me, Mine* me2) { }
int main() {
Mine* me = new Mine();
Mine* me2 = new Mine();
me->run(my_cb, me2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.