给定一个典型的类:
struct Whatever { void Doit(); }; Whatever w;
让成员函数被基于 C void* 的回调(例如 pthread_create() 或信号处理程序)调用的最佳方法是什么?
pthread_t pid; pthread_create(&pid, 0, ... &w.Doit() ... );
最佳答案
大多数 C 回调允许指定一个参数,例如
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
所以你可以拥有
void myclass_doit(void* x)
{
MyClass* c = reinterpret_cast<MyClass*>(x);
c->doit();
}
pthread_create(..., &myclass_doit, (void*)(&obj));
关于c++ - 让 C 回调调用 C++ 成员函数的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/140204/