2013-04-23 13 views
5

Sto lavorando su un profiler .NET che sto scrivendo in C++ (una DLL che utilizza ATL). Voglio creare un thread che scrive in un file ogni 30 secondi. Voglio che la funzione thread per essere un metodo di una delle mie classiCreare thread all'interno della DLL

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

quando provo ad avviare il thread

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

ho ottenuto questo errore:

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

Come correttamente creare un thread all'interno di una DLL? Qualsiasi aiuto sarebbe apprezzato.

+1

I puntatori di funzione e i puntatori alle funzioni membro sono molto diversi. Devi dichiarare la funzione membro come statica. –

+0

possibile duplicato di [Come usi CreateThread per le funzioni che sono membri della classe?] (Http://stackoverflow.com/questions/1372967/how-do-you-use-createthread-for-functions-which-are-class -Membri) –

risposta

7

Non è possibile passare un puntatore a una funzione membro come se fosse un puntatore a funzione regolare. Devi dichiarare la tua funzione membro come statica. Se è necessario chiamare la funzione membro su un oggetto, è possibile utilizzare una funzione proxy.

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); 
Problemi correlati