You can use a non-capturing lambda function with C-style APIs that expect a function pointer. As long as the signatures of the callback and the lambda match, the lambda will be cast to a function pointer (or you could define a “positive lambda”, one with a + in front of it; this causes automatic conversion to a function pointer). This works because the compiler converts non-capturing lambdas to actual functions and stores them inside the compiled binary. Effectively a pointer to locally defined lambda is valid for the life of the program.

In the program below I define a callback with the following signature: typedef void(*FuncPtr)(int arg) and two C-style functions that use it: void set_callback(FuncPtr fp) and void fire_callback(int arg). I then call set_callback with a positive lambda. The program works 🙂

c_api_lambda.cpp:

42

Program output.

Leave a Reply