c++ - 将方法作为函数指针传递

标签 c++ multithreading pointers function-pointers

Possible Duplicate:
function pointer for a member function

我有一个问题,在类里面,我有这个方法:virtual void start(void *(*ptr)(void*), void *);
在另一种情况下,我想使用此方法调用 start : void *Room::run(void *p)

所以我尝试这样做:thread->start(&Room::run, 0);但编译器不想要它,因为: cannot convert parameter 1 from 'void *(__thiscall Room::* )(void *)' to 'void *(__cdecl *)(void *)'

如何解决?模板?或者有更明显的解决方案吗?
谢谢 !

P.S:准确地说,我需要它来制作线程(http://linux.die.net/man/3/pthread_create)。

最佳答案

在 C++ 中,指向(独立)函数的指针和指向方法的指针是完全不同的东西,不能混合使用。

如果要将成员函数指针传递给需要函数指针的 API,那么典型的解决方案是使用小型包装函数:

class Room {
public:
  void run();
  // other members omitted

  // wrapper function
  static void* run_wrapper(void* p)
  {
    static_cast<Room*>(p)->run();
    return NULL;
  }
};

你可以像这样使用它:

thread->start(Room::run_wrapper, myRoomPointer);

关于c++ - 将方法作为函数指针传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14338534/

相关文章:

java - 为什么 wait , notify 和 notifyAll 方法都在 Object 类中?

c++ - 使用 volatile bool 强制另一个线程等待是否安全? (C++)

c++ - 指针内联的意思?

c++ - 翻转 bool : performance comparison of x=! x 与 x^=1

c++ - 从字符串中删除重复的字符

java - 关闭捕获全局输入事件的 Hook

C#:使用指针类型作为字段?

c - 函数中 malloc 和 sscanf 导致的 seg 错误

c++ - 如何在 C++ 中为共享计数器实现简单的比较和交换

c++ - 停止与 Windows 开始栏重叠的应用程序窗口