2

可能重复:
成员函数的函数指针

我有一个问题,在一个类中,我有这个方法: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 *)'

我该如何解决?模板?还是有更明显的解决方案?
谢谢 !

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

4

2 回答 2

3

在 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);
于 2013-01-15T13:21:25.430 回答
0

我强烈建议不要将函数指针转换为void *指针,因为在 c++ 和可能的 c 中,大小可能不同。

总的来说,您的解决方案不是很 C++。诚然,使用 ac 库有点棘手。这是我在当前项目中使用的方法:-

class ThreadBase
{
public:
  ThreadBase ()
  {
  }

  virtual ~ThreadBase ()
  {
    // TODO - inform thread to stop, using a message or a signal or something
    // and then wait for the thread to terminate
    void
      *return_value = 0;

    pthread_join (m_thread_handle, &return_value);
  }

  void Run ()
  {
    if (pthread_create (&m_thread_handle, 0, ThreadFunction, this))
    {
      // error - throw an exception or something
    }
  }

private:
  static void *ThreadFunction (void *param)
  {
    ThreadBase
      *thread = static_cast <ThreadBase *> (param);

    thread->Main ();

    return 0;
  }

  virtual void Main () = 0;

private:
  pthread_t
    m_thread_handle;
};

然后从 ThreadBase 派生实现特定版本:

class SomeThread : public ThreadBase
{
private:
  void Main ()
  {
    // do something
  }
};

您可能想要更改Main以返回退出代码并将其从线程传回。Main如果它处于无限循环中(例如,如果它是一个正在消耗某种消息的侦听器),您需要一种方法来退出。

于 2013-01-15T13:43:35.067 回答