gpt4 book ai didi

c++ - 如何将 void (__thiscall MyClass::* )(void *) 转换为 void (__cdecl *)(void *) 指针

转载 作者:太空狗 更新时间:2023-10-29 21:29:14 29 4
gpt4 key购买 nike

我想构建一个可以隐藏线程创建的“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);
}

找了半天也没弄明白。有没有人做过这样的事?还是我走错路了?时间差

最佳答案

你不能。

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

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

关于c++ - 如何将 void (__thiscall MyClass::* )(void *) 转换为 void (__cdecl *)(void *) 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5326251/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com