In a project, I have a C-API which uses C-style function pointers as callbacks. In one of those callbacks, I need to access a private function of an object Foo. Note that the API-call is done within a function of my class. Because of not shown code, I have a handle to my object as a void* accessible to me.
Things aside that the construct is prone to errors, by passing a lambda as callback I am able to access the private function of my object. This is somewhat unexpected but welcome to me. I haven't found anything regarding this behavior, so I would kindly ask if somebody could shed some light why this is actual working. I am not aware that the lambda is catching something, but it appears that is has something to do with the actual scoping. I am using C++17 and gcc 10.2.
Here's a sample block of code:
void TestFunc(void (*)(void*)) {
}
class Foo {
public:
Foo() {
TestFunc([](void* handle){
auto foo = reinterpret_cast<Foo*>(handle);
foo->BarFunc();
});
};
private:
void BarFunc() {};
};