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

标签 c++ multithreading

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

相关文章:

c++ - 在 C++ 中提高/优化文件写入速度

c++ - 类(class)问题,加一天

c++ - 基于自定义void_t实现的成员检测

android - 主线程正在等待 sqlcipher 游标关闭

c# - 计时器线程是等到回调函数中的所有步骤都完成还是回调函数在每个周期都被重新调用

c++ - Win32 处理来自 Rich Edit 控件的 WM_NOTIFY 消息

c++ - 在析构函数中抛出异常——有什么缺点?

java - 学习线程的资源

c++ - std::future 可以在没有 get 或 wait 的情况下导致 coredump

c - 当我用线程实现合并排序时得到不正确的输出,无法弄清楚出了什么问题