C++ pthreads - using code I used in C gives me a conversion error
I am running the same exact code that I ran in plain C:
pthread_create(&threads[i], &attr, SomeMethod, ptrChar);
And I get the errors:
error: invalid conversion from 'void*(
*)(char'*)' to 'void*(*)(void*)
'error: initializing argument 3 of 'int
pthread_create(__pthread_t**, __pthread_attr_t* conts*, void*(*)(void*), void*)'
SomeMethod is:
void *SomeMethod(char *direction)
Do I need to do something different in C++? I thought y开发者_如何学编程ou could just run any C code in C++ and it would work fine?
I am using Cygwin at the moment.
Like it says, they are two different function signatures. You should do:
void *SomeMethod(void* direction) // note, void
{
char* dir = static_cast<char*>(direction); // and get the value
}
C was casting from one function pointer to the other, apparently. Casting one function pointer to another is undefined behavior in C++.
That said, I'm pretty sure POSIX requires that casts between function pointers be well-defined, so you may be able to do this instead:
pthread_create(&threads[i], &attr, // cast the function pointer
reinterpret_cast<void* (*)(void*)>(SomeMethod), ptrChar);
Your thread function needs to be:
void *SomeMethod(void *direction);
And you can cast from void* to char* inside the function.
精彩评论