在DLL中创建线程

Kir*_*ira 5 c++ dll thread-sleep

我正在研究一个.NET分析器,我用c ++编写(一个使用ATL的DLL).我想创建一个每30秒写入一个文件的线程.我希望线程函数成为我的一个类的方法

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

当我尝试启动线程时

HANDLE l_handle = CreateThread( NULL, 0, MyThreadFunction, NULL, 0L, NULL );
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

argument of type "DWORD (__stdcall CProfiler::*)(void *pContext)" 
is incompatible with parameter of type "LPTHREAD_START_ROUTINE"
Run Code Online (Sandbox Code Playgroud)

如何在DLL中正确创建一个线程?任何帮助都会被贬低.

Cap*_*ous 8

您不能将指针传递给成员函数,就像它是常规函数指针一样.您需要将您的成员函数声明为static.如果需要在对象上调用成员函数,则可以使用代理函数.

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 );
Run Code Online (Sandbox Code Playgroud)