Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid conversion from ‘void*’ to ‘void* (*)(void*)’ c++?

Tags:

c++

pthreads

I am trying to use pthread_create() but it always gives me this error invalid conversion from void* to void* ( * )(void*)

This error is in the 3rd argument. Could someone help me with this error ?

void Print_data(void *ptr) {
    cout<<"Time of Week = " <<std::dec<<iTOW<<" seconds"<<endl;
    cout<<"Longitude = "<<lon<<" degree"<<endl;
    cout<<"Latitude  = "<<lat<<" degree"<<endl;
    cout<<"Height Above Sea = "<<alt_MSL<<" meters"<<endl;    
  }

int call_thread() 
  {
    pthread_create(&thread, NULL, (void *) &Print_data, NULL);
    return 0;
  }
like image 918
Zeyad Avatar asked Jun 17 '13 12:06

Zeyad


Video Answer


2 Answers

The error is that you're converting the function pointer (void* (*)(void*)) to an object pointer (void*), when pthread_create expects a function pointer for that argument. There's no implicit conversion to undo the dodgy conversion you've done, hence the error.

The answer is to not do that:

pthread_create(&thread, NULL, &Print_data, NULL);

and you'll also need to modify Print_data to return void* to match the Posix threads interface:

void *Print_data(void *ptr) {
    // print stuff
    return NULL;  // or some other return value if appropriate
}

As noted in the comments, there are various other issues with using this C library directly from C++; in particular, for portability, the thread entry function should be extern "C". Personally, I'd recommend using the standard C++ thread library (or Boost's implementation, if you're stuck with a pre-2011 version of the language).

like image 93
Mike Seymour Avatar answered Oct 25 '22 14:10

Mike Seymour


You're trying to convert a function pointer into a void* here: (void *) &Print_data

According to pthread_create you need to pass in a function that takes a void* and returns a void*

So your function signature should be

void* Print_data(void *ptr) 

And your call should be

pthread_create(&thread, NULL, &Print_data, NULL);
like image 41
Salgar Avatar answered Oct 25 '22 15:10

Salgar