How can I pass a C++ lambda to a C-callback that expects a function pointer and a context?

Viewed 19092

I'm trying to register a callback in a C-API that uses the standard function-pointer+context paradigm. Here's what the api looks like:

void register_callback(void(*callback)(void *), void * context);

What I'd really like to do is be able to register a C++ lambda as the callback. Additionally, I want the lambda to be one that has captured variables (ie. can't be converted to a straight stateless std::function)

What kind of adapter code would I need to write to be able to register a lambda as the callback?

4 Answers

A lambda function is compatible with C-callback function as long as it doesn't have capture variables.
Force to put something new to old one with new way doesn't make sense.
How about following old-fashioned way?

typedef struct
{
  int cap_num;
} Context_t;

int cap_num = 7;

Context_t* param = new Context_t;
param->cap_num = cap_num;   // pass capture variable
register_callback([](void* context) -> void {
    Context_t* param = (Context_t*)context;
    std::cout << "cap_num=" << param->cap_num << std::endl;
}, param);
Related