The easiest way to handle this is to create a "stub" function which calls back into your class.
UINT tid
HANDLE hThread = CreateThread(NULL, 0, myThreadStub, this, 0, &tid);
....
unsigned long WINAPI myThreadStub(void *ptr)
{
if (!ptr) return -1;
return ((MyClass*)ptr)->ThreadMain();
}
CreateThread() allows you to pass an argument to the thread function (parameter 4 of the CreateThread() call). You can use this to pass a pointer to your class. You can then have the thread stub cast that pointer back into the proper type and then call a member function. You can even have "myThreadStub" be a static member of "MyClass", allowing it
to access private members and data.
If you have boost installed, you may be able to use boost::bind to do this without creating a stub function. I've never tried that on windows, so I can't say for sure it would work (because the callback function must be a WINAPI call) but if it does work it would look something like:
HANDLE hThread = CreateThread(NULL, 0, boost::bind(&MyClass::ThreadFunction, this), NULL, 0, &tid);
Where thread function is a non-static member function which takes a single void * argument.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…