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. Subclass implements the "Thr开发者_Go百科eadMain" method and make it called automatically which seems like this:
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
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));
}
精彩评论