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 🙂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> using namespace std; typedef void(*FuncPtr)(int arg); FuncPtr callback; void set_callback(FuncPtr fp) { callback = fp; } void fire_callback(int arg) { callback(arg); } int main() { set_callback(+[](int arg) { cout << arg << endl; }); fire_callback(42); } |
42
Program output.