[英]How to convert void (__thiscall MyClass::* )(void *) to void (__cdecl *)(void *) pointer
我想構建一個可以隱藏線程創建的“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
你不能。
您應該使用靜態函數(不是靜態成員函數,而是自由函數)。
// 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.