Create thread in DLL

I am working on a .NET profiler, which I write in C ++ (a DLL using ATL). I want to create a stream that is written to a file every 30 seconds. I want the stream 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 a 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 create a thread in a DLL? Any help would be appreciated.

+5
source share
1 answer

You cannot pass a pointer to a member function as if it were a regular function pointer. You must declare your member function as static. If you need to call a 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 );
+7
source

All Articles