CreateThread Wrapper for object methods

Hey folks,

I'm a bit desperate. I'd like to call an object method via CreateThread. Therefore I started writing a simple template wrapper class. But at the key position I'm getting an Access Violation Error.
The following works:
1
2
3
4
5
6
7
8
	
// Server.cpp
/* ... */
DWORD ( Server::* method)(void) = &Server::wait_for_clients;
Server* THIS = this;
(THIS->*method)();
/* ... */
DWORD wait_for_clients(){ /* ... */ } 	

I tried to adapt this to make my template work:
1
2
3
4
5
// Server.cpp
/* ... */
Thread_Wrapper<Server> wrap(this, &Server::wait_for_clients);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Thread_Wrapper<Server>::start, (LPVOID)&wrap, 0, NULL);
/* ... */ 	

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Thread_Wrapper.h
#include <WinDef.h>
template<class T>
class Thread_Wrapper
{
public:
	T* object;
	DWORD ( T::* method)(void);
public:
	static DWORD start(LPVOID thread_wrapper_obj)
	{
		Thread_Wrapper<T>* wrap = (Thread_Wrapper<T>*)thread_wrapper_obj;
		T* object = wrap->object;
		DWORD ( T::* method)(void) = wrap->method;
		(object->*method) ();
		return 0;
	}
	Thread_Wrapper(T* object, DWORD ( T::* method)(void))
	{
		this->object = object;
		this->method = method;
	}
	~Thread_Wrapper(void){}
}; 	

But (object->*method) (); throws an Access Violation Error. I haven't the faintest idea why. There has to be something I'm missing here!?!?

Thank you very much
Nico
You may call me idiot :D
Thread_Wrapper<Server> wrap(this, &Server::wait_for_clients);
I placed the object on the stack :D Therefore the object was destroyed before the concurrent thread could invoke the required method...
Works fine if I place the object on the heap or if i give it a global scope :)
Topic archived. No new replies allowed.