简体   繁体   中英

Differences between Pthread in C vs C++

So I was able to pass an Ada function using Ada_function'Address to a C_function. Here is the C function:

void Create_Process(int * status, void * function) {
    pthread_t new_thread;

    //creating function with the given function and no arguments.
    *status = pthread_create(&new_thread, NULL, function, NULL);
}

This worked perfectly fine. My problem is when I try to use this same function in C++. It fails at compiling with the error:

error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’ [-fpermissive]
*status = pthread_create(&new_thread, NULL, function, NULL);

Is there any reason that this works / compiles in C but not C++?

Implicit type conversions in C++ are much more strict than in C. The void * function parameter can't be used as function pointer in C++ or C...

You need void* (*function)(void*) in your function prototype.

As mentioned by KIIV implicit type conversions in C++ are much more strict than in C.

void* (*function) (void*)

This is a pointer to a function which takes one void* argument and returns void* .

To get rid of your errors in C++, change your function to return void * , and pass it without type-casting it. The return from the thread function can be a simple return NULL if you don't care about the value.

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" . Good practice should be using the standard C++ thread library (or Boost's implementation, if you're stuck with a pre-2011 version of the language).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM