tags:

views:

148

answers:

2

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 you could just run any C code in C++ and it would work fine?

I am using Cygwin at the moment.

+6  A: 

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);
GMan
There's no implicit conversion between function pointer types, so it's not undefined (it's just not allowed). The call through the `reinterpret_cast` function pointer is undefined, however: "A pointer to a function can be explicitly converted to a pointer to a function of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined" (5.2.10/6).
James McNellis
@James: Ya, that's what I meant by "think this is undefined behavior in C++, but I'm not sure on that.", except now I'm more sure of it. :) I wonder why it worked in C, though. I still maintain that POSIX requires such a cast to work, though.
GMan
+4  A: 

Your thread function needs to be:

void *SomeMethod(void *direction);

And you can cast from void* to char* inside the function.

jeffamaphone