2011-03-16 95 views
3

我想构建一个可以隐藏线程创建的“IThread”类。子类实现“ThreadMain”方法,并自动调用它看起来像这样:如何将void(__thiscall MyClass :: *)(void *)转换为void(__cdecl *)(void *)指针

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

OP没有使用搜索 – zabulus 2011-03-16 13:53:46

回答

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)); 
} 
+0

静态成员函数将无法正常工作,如果你有一个符合的编译器。 _beginthread可能需要一个extern“C”函数,而一个静态成员不能有“C”链接。 (当然,_beginthread是一个Windows特定的函数,而VC++并不考虑extern“C”,所以你可能不会遇到任何问题。) – 2011-03-16 14:00:55

+0

我使用了一个静态函数,而不是静态成员函数。他们可以有“C”连接。在这种情况下,使用或不使用“extern”C“'的区别可能仅仅是符号表中的不同名称。尽管我会更新我的答案。 – 2011-03-16 14:06:12

+0

@詹姆斯:好奇,你是对的。但是它有什么实际用途吗?有没有C和C++链接不兼容的编译器? – 2011-03-16 14:21:38

相关问题