_beginthreadex静态成员函数(_beginthreadex static member

2019-07-31 22:27发布

如何创建一个静态成员函数的线程程序

class Blah
{
    static void WINAPI Start();
};

// .. 
// ...
// ....

hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL);

这给了我下面的错误:

***error C2664: '_beginthreadex' : cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)'***

我究竟做错了什么?

Answer 1:

有时候,看你得到的错误是有用的。

cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)'

让我们来看看它说什么。 对于参数三,你给它一个函数签名void(void) ,也就是一个函数,它不带任何参数,并且没有返回。 它无法将其转换为unsigned int (__stdcall *)(void *) ,这是什么_beginthreadex 预期

它需要一个函数:

  • 返回一个unsigned int
  • 采用stdcall调用约定
  • 需要一个void*说法。

所以我的建议是“把它与它的要求签名的功能”。

class Blah
{
    static unsigned int __stdcall Start(void*);
};


Answer 2:

class Blah
{
    static unsigned int __stdcall Start(void*); // void* should be here, because _beginthreadex requires it.
};

传递给该例程_beginthreadex必须使用__stdcall调用约定,并且必须返回一个线程退出代码

胡说的实现::开始:

unsigned int __stdcall Blah::Start(void*)
{
  // ... some code

  return 0; // some exit code. 0 will be OK.
}

后来在你的代码,你可以写任何如下:

hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL);
// or
hThread = (HANDLE)_beginthreadex(NULL, 0, &CBlah::Start, NULL, NULL, NULL);

在第一种情况下Function-to-pointer conversion将根据C ++标准4.3 / 1来施加。 在第二种情况下,你会传递指针隐含的功能。



Answer 3:

class Blah
{
  public:
    static DWORD WINAPI Start(void * args);
};


Answer 4:

以下是编译的版本:

class CBlah
{
public:
    static unsigned int WINAPI Start(void*)
    {
    return 0;
    }
};

int main()
{
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &CBlah::Start, NULL, NULL, NULL);

    return 0;
}

以下是所需的改变:

(1)。 启动()函数将返回unsigned int类型

(2)。 它应该采取一个void *作为参数。

编辑

删除点(3),按照评论



Answer 5:

class Blah
{
    static unsigned int __stdcall Start(void *);
};


文章来源: _beginthreadex static member function