在DLL中创建线程

Create thread within DLL

本文关键字:线程 创建 DLL      更新时间:2023-10-16

我正在用c++(一个使用ATL的dll)编写。net分析器。我想创建一个线程,每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中正确创建线程?

不能将指针作为普通函数指针传递给成员函数。您需要将成员函数声明为静态的。如果需要在对象上调用成员函数,可以使用代理函数。

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