problems using CreateThread on a member function

蹲街弑〆低调 提交于 2019-12-02 12:34:57

问题


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

this is what I am trying:

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

    };

回答1:


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.

So you could do

ping_thread = CreateThread (NULL , 0, ping_loop, (LPVOID)this, 0, &dping_thread);

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
}


来源:https://stackoverflow.com/questions/8025049/problems-using-createthread-on-a-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!