Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

nPawn

Windows CreateThread( ) question

This topic is 5333 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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)

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!