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

前端 未结 4 899
面向向阳花
面向向阳花 2020-12-05 02:43

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_callba         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 02:47

    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);
    

提交回复
热议问题