在DLL中创建线程

时间:2013-04-23 10:57:01

标签: c++ dll thread-sleep

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

的方法
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 个答案:

答案 0 :(得分: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 );
相关问题