_Beginthreadex static member function
How to create a thread procedure for a static member function
class Blah
{
static void WINAPI Start();
};
// ..
// ...
// ....
hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL);
This gives me the following error:
***error C2664: '_beginthreadex' : cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)'***
What am I doing wrong?
source to share
It is sometimes helpful to read the error you are getting.
cannot convert parameter 3 from 'void (void)' to 'unsigned int (__stdcall *)(void *)'
See what he says. For parameter three, you give it a function with a signature void(void)
, that is, a function that takes no arguments and returns nothing. It cannot convert this value to unsigned int (__stdcall *)(void *)
, which means _beginthreadex
:
It expects a function that:
- Returns
unsigned int
: - Uses a calling convention
stdcall
- Accepts an argument
void*
.
So my suggestion would be "give it the signature function it asks for."
class Blah
{
static unsigned int __stdcall Start(void*);
};
source to share
class Blah
{
static unsigned int __stdcall Start(void*); // void* should be here, because _beginthreadex requires it.
};
The procedure passed to _beginthreadex
must use the calling convention __stdcall
and must return a thread exit code .
Blah :: Start implementation:
unsigned int __stdcall Blah::Start(void*)
{
// ... some code
return 0; // some exit code. 0 will be OK.
}
Later in the code, you can write any of the following:
hThread = (HANDLE)_beginthreadex(NULL, 0, CBlah::Start, NULL, NULL, NULL);
// or
hThread = (HANDLE)_beginthreadex(NULL, 0, &CBlah::Start, NULL, NULL, NULL);
In the first case, it Function-to-pointer conversion
will be applied in accordance with the C ++ Standard 4.3 / 1. In the second case, you will be passing the function pointer implicitly.
source to share
Below is the compiled version:
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;
}
Following are the required changes:
(1). Start () function must return unsigned int
(2). It must take a void * value as a parameter.
EDIT
Remote point (3) as per comment
source to share