如何创建一个静态成员函数的线程程序
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 *)'***
我究竟做错了什么?
有时候,看你得到的错误是有用的。
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*);
};
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来施加。 在第二种情况下,你会传递指针隐含的功能。
class Blah
{
public:
static DWORD WINAPI Start(void * args);
};
以下是编译的版本:
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),按照评论
class Blah
{
static unsigned int __stdcall Start(void *);
};