2013-04-23 199 views
5

我正在使用C++編寫的.NET分析器(使用ATL的dll)。我想創建一個每隔30秒寫入一個文件的線程。我想線程函數是我的一個類的方法在DLL中創建線程

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

當我嘗試啓動線程

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

我得到這個錯誤:

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

如何正確在DLL中創建一個線程? 任何幫助將被折衷。

+1

函數指針和指向成員函數的指針有很大不同。您需要將成員函數聲明爲靜態。 – 2013-04-23 11:00:11

+0

[你如何使用CreateThread函數是類成員?](http://stackoverflow.com/questions/1372967/how-do-you-use-createthread-for-functions-which-are-class - 成員) – 2013-04-23 11:01:07

回答

7

不能將指針傳遞給成員函數,就像它是常規函數指針一樣。你需要聲明你的成員函數是靜態的。如果您需要在對象上調用成員函數,則可以使用代理函數。

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