_beginthread; How do I pass member function as parameter?

Here's my function:
void Incoming(socketDataStruct *socketData);

..and here's how I try to pass it:

_beginthread((void(__cdecl*)(void*))Incoming, 0, &socketData);

It worked fine until I put Incoming into a class called Server. Now I'm getting a conversion error.

error C2440: 'type cast' : cannot convert from 'overloaded-function' to 'void (__cdecl *)(void *)'
until I put Incoming into a class called Server.

I take it that you mean that you made Incoming a normal member of class Server?

_beginthread can only accept a normal function pointer, not a pointer to class member, which means that Incoming must be either a regular function or a static class member.

The usual trick it to pass the this pointer as the start up parameter to _beginthread (or _beginthreadex).

See this post for an example:

_beginthread
http://www.cplusplus.com/forum/general/6989/#msg32614

Also note that the example in this post uses _beginthreadex rather than _beginthread, which is preferred in new code (the non -ex version is to support legacy code only.)

Andy
Last edited on
It worked. :)

Thank you sir.
PS Just noticed you using a cast when calling _beginthread.

It is safer to keep the standard signature and then cast the pointer that arrives at your start function. Then the compiler will spot if the function signature is out of step with the one required, esp. wrt calling convention.

It is also one of the cases where I explictly declare the calling convention, on the off chance the default calling convention changes (esp. if code gets cut and pasted to another module?).

1
2
3
4
5
6
7
8
unsigned __stdcall Incoming(void* param)
{
  socketDataStruct *socketData = reinterpret_cast<socketDataStruct *>(param);

  // use code

  return 0; // or suitable return code
}

and

_beginthread(0, 0, Incoming, &socketData, 0, &threadid);

(threadid is an unsigned in)

Andy
Last edited on
Topic archived. No new replies allowed.