5

I'm working on a .NET profiler which I'm writing in c++ (a dll that uses ATL). I want to create a thread that writes into a file every 30 seconds. I want the thread function to be a method of one of my classes

DWORD WINAPI CProfiler::MyThreadFunction( void* pContext )
{
   //Instructions that manipulate attributes from my class;
}

when I try to start the thread

HANDLE l_handle = CreateThread( NULL, 0, MyThreadFunction, NULL, 0L, NULL );

I got this error :

argument of type "DWORD (__stdcall CProfiler::*)(void *pContext)" 
is incompatible with parameter of type "LPTHREAD_START_ROUTINE"

How to properly create a thread within a DLL? Any help would be apreciated.

Kira
  • 1,153
  • 4
  • 28
  • 63
  • 1
    function pointers and pointers to member functions are very different. You need to declare the member function as static. – Captain Obvlious Apr 23 '13 at 11:00
  • possible duplicate of [How do you use CreateThread for functions which are class members?](http://stackoverflow.com/questions/1372967/how-do-you-use-createthread-for-functions-which-are-class-members) – Some programmer dude Apr 23 '13 at 11:01

1 Answers1

8

You cannot pass a pointer to a member function as if it were a regular function pointer. You need to declare your member function as static. If you need to call the member function on an object you can use a proxy function.

struct Foo
{
    virtual int Function();

    static DWORD WINAPI MyThreadFunction( void* pContext )
    {
        Foo *foo = static_cast<Foo*>(pContext);

        return foo->Function();
     }
};


Foo *foo = new Foo();

// call Foo::MyThreadFunction to start the thread
// Pass `foo` as the startup parameter of the thread function
CreateThread( NULL, 0, Foo::MyThreadFunction, foo, 0L, NULL );
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74