Skip to content

Instantly share code, notes, and snippets.

@moleike
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moleike/d5a89765e44c1829ce21 to your computer and use it in GitHub Desktop.
Save moleike/d5a89765e44c1829ce21 to your computer and use it in GitHub Desktop.
Lambda in a C callback
#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