Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create thread within DLL

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.

like image 511
Kira Avatar asked Apr 23 '13 10:04

Kira


People also ask

Can you have threads in a DLL?

Definitely! A process maps a DLL into its address spaces. Threads created within the DLL are part of the host's process address spaces.

What is create thread?

The CreateThread function creates a new thread for a process. The creating thread must specify the starting address of the code that the new thread is to execute.

How do you create a thread in C++?

To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable. After defining callable, pass it to the constructor.

Can we create thread inside thread C++?

A thread does not operate within another thread. They are independent streams of execution within the same process and their coexistence is flat, not hierarchical. Some simple rules to follow when working with multiple threads: Creating threads is expensive, so avoid creating and destroying them rapidly.


1 Answers

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 );
like image 64
Captain Obvlious Avatar answered Oct 10 '22 21:10

Captain Obvlious