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

发布于 2024-10-22 14:39:37 字数 674 浏览 1 评论 0原文

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

I want to build a "IThread" class which can hide the thread creation. Subclass implements the "ThreadMain" 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泅人 2024-10-29 14:39:37

你不能。

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

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

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));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文