问题使用CreateThread在成员函数上 [英] problems using CreateThread on a member function
问题描述
我试图在一个对象中创建一个线程,但是我收到一个错误,说'&':绑定成员函数表达式的非法操作。
我必须使成员函数静态,但是当我这样做,我得到一个错误,说'dac_ping'的左边必须有类/ struct / union
I am trying to create a thread in an object, however I get an error saying '&' : illegal operation on bound member function expression.
Reading up I saw I have to make the member function static, but when I do that I get an error saying left of '.dac_ping' must have class/struct/union
这是我想要的:
class Dac
{
private:
network_com com;
HANDLE ping_thread;
DWORD dping_thread;
static DWORD WINAPI ping_loop(void* param)
{
while ( com.dac_ping() == 0)
Sleep(900);
return 1; //since this is an infinite loop, if the loop breaks, it has failed
}
public:
Dac()
{
}
~Dac()
{
}
void find_dac()
{
com.find_dac();
com.print_dac_info();
}
void connect_and_keep_alive()
{
if (com.dac_connect() == 0)
ping_thread = CreateThread (NULL , 0, ping_loop, NULL, 0, &dping_thread);
}
};
推荐答案
static
函数不绑定到特定实例;没有这个
指针,并且没有成员变量。您可以将 this
指针作为参数传递给函数,然后将其转换为 Dac *
static
functions aren't bound to a particular instance; there is no this
pointer, and you have no "member variables." You can pass the this
pointer as an argument to your function, and then cast it into a Dac*
and access member variables from it.
因此,您可以执行
ping_thread = CreateThread (NULL , 0, ping_loop, (LPVOID)this, 0, &dping_thread);
并将 ping_loop
更改为: / p>
And change your ping_loop
to this:
static DWORD WINAPI ping_loop(void* param)
{
Dac* dac = (Dac*)param;
while ( dac->com.dac_ping() == 0)
Sleep(900);
return 1; //since this is an infinite loop, if the loop breaks, it has failed
}
这篇关于问题使用CreateThread在成员函数上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!