简体   繁体   English

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

[英]How to convert void (__thiscall MyClass::* )(void *) to void (__cdecl *)(void *) pointer

I want to build a "IThread" class which can hide the thread creation. 我想构建一个可以隐藏线程创建的“IThread”类。 Subclass implements the "ThreadMain" method and make it called automatically which seems like this: 子类实现“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);
}

I have searched around and cannot figure it out. 我四处搜寻,无法弄明白。 Is there anybody who did such thing? 有没有人做过这样的事情? Or I am going the wrong way? 或者我走错了路? TIA TIA

You can't. 你不能。

You should use a static function instead (not a static member function, but a free function). 您应该使用静态函数(不是静态成员函数,而是自由函数)。

// 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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM