0

I have a c++ class as below. I am attempting to setup a thread as such below, where my callback (the void pointer function) is within the class. This throws an error on the pthread_create function where it says

cannot convert from type void*(Ball::)(void*) to type void*()(void)

class Ball
{
    private: struct BallMsg ballMsg;
    private: pthread_t ballThread;


    public: Ball(int id)
    {
        ballMsg.id = id;
        ballMsg.r = 7;
        ballMsg.x = 60 + (455/2) - 30;
        ballMsg.y = 60 + 10 + 5 + ballMsg.r;
        ballMsg.c = 0xFFFF0000;
        ballMsg.vel = 5.0;
        ballMsg.ang = 45.0;

        int ret;
        ret = pthread_create(&ballThread, NULL, this->ball_thread, NULL);
        if (ret !=0)
        {
            xil_printf("Error launching thread 1\r\n");
        }
    }

    public: void *ball_thread(void *arg)
    {
        int i = 0;
        while(1)
        {
            //unsigned int tval = sys_time(NULL);
            //xil_printf("%d : Time is: %d\r\n", i++, tval);
        }
    }

    public: ~Ball()
    {

    }
};
raaj
  • 2,869
  • 4
  • 38
  • 58
  • Wow..unbelievable. I just got banned from stack overflow because you marked this as duplicate. Any way around this? – raaj Mar 22 '15 at 04:02

1 Answers1

3

pthread_create expects a pointer to a non-member function, but void *ball_thread is a member of Ball. That means it needs a Ball object to be called on an so has a fundamentally different structure to a non-member.

You can use std::thread instead, which makes it easy to bind an object to a member function.

Alternatively, you can the ball_thread function a non-member, and pass a Ball* first parameter if required.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • unfortunately this is for an embedded platform which doesn't support std::thread. What option do i have now? I have to make it static? – raaj Mar 21 '15 at 07:31
  • @raaj Yes, you do. But you could use the thread argument (`arg`) to pass the object pointer. – user253751 Mar 21 '15 at 07:33
  • how can i do that? just pass in "this"? If so how can i cast and get my object back? – raaj Mar 21 '15 at 07:36
  • @raaj do you know how casts and void* work? – user253751 Mar 21 '15 at 07:45
  • i think so. passing this in is passing the current object's address into the thread to reference. from there i did this. Ball *ball = static_cast(arg); – raaj Mar 21 '15 at 08:04