如何将void(__thiscall MyClass :: *)(void *)转换为void(__ cdecl *)(void *)指针

时间:2011-03-16 13:47:43

标签: c++ multithreading

我想构建一个可以隐藏线程创建的“IThread”类。子类实现“ThreadMain”方法并使其自动调用,如下所示:

class IThread
{
public:
    void BeginThread();
    virtual void ThreadMain(void *) PURE;
};
void IThread::BeginThread()
{
    //Error : cannot convert"std::binder1st<_Fn2>" to "void (__cdecl *)(void *)"
    m_ThreadHandle = _beginthread(
                     std::bind1st( std::mem_fun(&IThread::ThreadMain), this ),
                     m_StackSize, NULL);
    //Error : cannot convert void (__thiscall* )(void *) to void (__cdecl *)(void *)
      m_ThreadHandle = _beginthread(&IThread::ThreadMain, m_StackSize, NULL);
}

我四处搜寻,无法弄明白。有没有人做过这样的事情?或者我走错了路? TIA

1 个答案:

答案 0 :(得分:3)

你不能。

您应该使用静态函数(不是静态成员函数,而是自由函数)。

// IThread.h
class IThread
{
public:
    void BeginThread();
    virtual void ThreadMain() = 0;
};

// IThread.cpp
extern "C"
{
    static void __cdecl IThreadBeginThreadHelper(void* userdata)
    {
        IThread* ithread = reinterpret_cast< IThread* >(userdata);
        ithread->ThreadMain();
    }
}
void IThread::BeginThread()
{
    m_ThreadHandle = _beginthread(
                     &IThreadBeginThreadHelper,
                     m_StackSize, reinterpret_cast< void* >(this));
}