c++ - 让 C 回调调用 C++ 成员函数的最佳方法?

标签 c++ function struct callback

给定一个典型的类:

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/

相关文章:

c++ - 在没有 static_cast<> 的派生类中重载 std::ostream& operator<<

c++ - Visual Studio下CMake构建问题

Javascript 滑入加载

javascript - 我想知道学生数组中是否有某个名字,如果有则打印出true,如果没有则打印出false

c++ - 自定义 STL 序列的最小嵌套 typedef 集?

c++ - 从 C 结构生成 HTML 页面

php函数返回0?

c - 从文件中读取 7 个变量(每个变量 1 行)并分配给结构变量

c++ - 在 C++ 中打印 BST 的函数

c# - 数组和列表与结构的差异