Last active
August 29, 2015 14:22
-
-
Save moleike/d5a89765e44c1829ce21 to your computer and use it in GitHub Desktop.
Lambda in a C callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <functional> | |
#include <iostream> | |
// using a lambda in a C callback | |
extern "C" void | |
register_callback (void (*callback)(void *), void * context) | |
{ | |
// for simplicity we just call it | |
callback (context); | |
} | |
extern "C" void | |
invoke_function (void* ptr) | |
{ | |
(*static_cast<std::function<void()>*>(ptr))(); | |
} | |
class example | |
{ | |
public: | |
example (int val) : a(val) | |
{ | |
register_callback (invoke_function, | |
new std::function<void()>([=](){ | |
std::cout << "value is " << a; | |
}) | |
); | |
} | |
private: | |
int a; | |
}; | |
int main() | |
{ | |
example ex(42); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment