Windows CreateThread( ) question

Started by
2 comments, last by nPawn 20 years, 3 months ago
Is it possible to pass a class function to CreateThread in Windows? CreateThread works great with a function that isn''t a member of a class sent to it, but as soon as I try sending a class function it complains.

bool CThing::Start(int intPort)
{
	HANDLE handle = NULL;
		
        handle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Listen, 0, 0, 0);
	
	if (!handle)
	{
		return false;
	}
	return true;
}

void CThing::Listen(LPVOID lpvParam)
{
     ...
}
the above fails, with the error: error C2440: ''type cast'' : cannot convert from ''overloaded-function'' to ''LPTHREAD_START_ROUTINE'' Doesn''t matter if I type cast it to ''LPTHREAD_START_ROUTINE'' or not, it complains. Whereas if I make the Listen function not part of the class it works great:

void Listen(LPVOID lpvParam)
{
     ...
}


bool CThing::Start(int intPort)
{
	HANDLE handle = NULL;
		
        handle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Listen, 0, 0, 0);
	
	if (!handle)
	{
		return false;
	}
	return true;
}
Is there any way to get a class function working with CreateThread? (This is VC7.0 btw)
Advertisement
First, you will probably have to invoke CreateThread() as:

CreateThread(0,0,CThing::Listen,0,0,0);

If that alone doesn''t fix it, your problem is the fact that CThing::Listen() is not static and is therefore recieving an implicit ''this'' parameter. Making it static should fix that.
Ahh, you''re right, after digging around I find the class function needs to be static for createthread to like it. Why is this I wonder? I suppose maybe i''ll pass this as a parameter and get back to my class that way.
Remember that under Windows every thread has it''s own stack, so don''t pass a "this" pointer unless it was allocated from the heap - constructed via "new" and not as a local variable.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man

This topic is closed to new replies.

Advertisement