|
-
November 24th, 2002, 08:25 AM
#1
CreateThread and Winsock Question
I was looking at the Winsock FAQ (http://tangentsoft.net/wskfaq/) and they had an example for a simple multi threaded server. I complied it and it worked fine. I then made a new project and made a threaded server class, CServer. When I compiled it the line
CreateThread(0, 0, EchoHandler, (void*)sd, 0, &nThreadID);
generated the error
error C2664: 'CreateThread' : cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__stdcall *)(void *)'
None of the functions with this name in scope match the target type
the prototype for the function is
DWORD WINAPI CServer::EchoHandler(void* sd_)
its the exact same as in the example except for the 'CServer::' does anyone have any ideas why this won't work? Thanks in advance
James
-
November 24th, 2002, 08:41 AM
#2
You can't pass a C++ method to CreateThread. You need to do something like this:
Code:
void CServer::Something()
{
...
CreateThread(0, 0, ::EchoHandler, (void*)this, 0, &nThreadID);
...
}
DWORD WINAPI CServer::EchoHandler()
{
// do your stuff here
}
// Wrapper function
DWORD WINAPI EchoHandler(void *classPtr)
{
CServer *server = (CServer *)classPtr;
return server->EchoHandler();
}
-
November 24th, 2002, 11:54 AM
#3
There are several solution. Before we explore one solution, I recommend that you use _beginthreadex() instead of CreateThread(). _beginthreadex() from C/C++ run-time library cleans up memory after you use any functions from the library.
Here is one solution.
Code:
unsigned _stdcall CServer::EchoHandler();
struct EchoParam
{
// Whatever you want to pass in the callback function.
};
DWORD threadID = 0;
EchoParam *ptp = new EchoParam;
...
HANDLE hThread = reinterpret_cast<HANDLE>(
_beginthreadex(// Default security
NULL,
0,
// Callback function
EchoHandler,
// Callback function paramater.
reinterpret_cast<void *>(ptp),
// Initial flags
0,
// Thread ID
&threadID));
Kuphryn
Last edited by kuphryn; November 24th, 2002 at 11:57 AM.
-
November 24th, 2002, 02:05 PM
#4
Re: CreateThread and Winsock Question
Originally posted by jamesbr
CreateThread(0, 0, EchoHandler, (void*)sd, 0, &nThreadID);
generated the error
error C2664: 'CreateThread' : cannot convert parameter 3 from 'unsigned long (void *)' to 'unsigned long (__stdcall *)(void *)'
None of the functions with this name in scope match the target type
It looks like 'EchoHandler()' is a member function of your class. In this case it needs to be static in order to be used as a thread function. Further explanation can be found in the FAQ...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|