Skip to content

Instantly share code, notes, and snippets.

@matutter
Created May 21, 2019 02:04
Show Gist options
  • Select an option

  • Save matutter/1577488f29e0cddfc8d4b5c2c80bcdd5 to your computer and use it in GitHub Desktop.

Select an option

Save matutter/1577488f29e0cddfc8d4b5c2c80bcdd5 to your computer and use it in GitHub Desktop.
Example of using C++ lambdas with closure as classic C function pointers.
#include <iostream>
#include <functional>
typedef int (*int_fn_t)(int);
extern "C" void c_call(int_fn_t fn);
void c_call(int_fn_t fn) {
std::cout << fn(0) << std::endl;
}
typedef void (*void_fn_t)(void);
extern "C" void c_call_v(void_fn_t fn);
void c_call_v(void_fn_t fn) {
fn();
}
int c_fn(int a, int b) {
std::cout << a << " " << b << std::endl;
return a + b;
}
int main(void) {
// normal call
c_fn(1, 2);
c_call([](int i) {
return i + 3;
});
auto b1 = std::bind(&c_fn, 4, std::placeholders::_1);
b1(5);
//c_call(b1); // Does not work because calling conventions do not match
int x = 7;
auto b2 = [x]() {
std::cout << x << std::endl;
};
// c_call_v(&b2); // Same
int z = 67;
// the closed lambda is static. We would have to have this declared outside
// a function to make it useful.
static auto lambda = [=]() {
std::cout << z << std::endl;
};
void (*wrapped_lambda)() = []() { lambda(); };
c_call_v(wrapped_lambda); // nice but can we do better?
// Yes with some macro magic.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment