Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method to have a C++ member function get called by a C callback ?

Given a typical class:

struct Whatever
{
    void Doit();
};

Whatever w;

what is the best way to get the member function to be called by a C void* based callback such as pthread_create() or a signal handler ?

pthread_t pid;

pthread_create(&pid, 0, ... &w.Doit() ... );
like image 563
keraba Avatar asked Nov 29 '22 20:11

keraba


1 Answers

Most C callbacks allow to specify an argument e.g.

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine)(void*), void *arg);

So you could have

void myclass_doit(void* x)
{
  MyClass* c = reinterpret_cast<MyClass*>(x);
  c->doit();
}

pthread_create(..., &myclass_doit, (void*)(&obj));
like image 166
Ian G Avatar answered Dec 15 '22 04:12

Ian G