tags:

views:

308

answers:

3

This is somewhat similiar to this : http://stackoverflow.com/questions/1151582/pthread-function-from-a-class

But the function that's getting called in the end is referencing the this pointer, so it cannot be made static.

void * Server::processRequest()
{
     std::string tmp_request, outRequest;
     tmp_request = this->readData();
     outRequest = this->parse(tmp_request);
     this->writeReply(outRequest);
}

void * LaunchMemberFunction(void * obj)
{
    return ((Server *)obj)->processRequest();
}

and then the pthread_create

Server SServer(soc);

pthread_create(&handler[tcount], &attr, (void*)LaunchMemberFunction,(void*)&SServer);

errors:

SS_Twitter.cpp:819: error: invalid conversion from void* to void* ()(void) SS_Twitter.cpp:819: error: initializing argument 3 of int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)

+1  A: 

You are casting the third argument to a void* ((void*)LaunchMemberFunction), and then getting an error as void* cannot cast to a function pointer. I believe it should compile if you just use &LaunchMemberFunction.

Todd Gardner
A: 

get rid of the (void*) in front of LaunchMemberFunction. It's both unecessary and incorrect, and the cause of your error. The language will not implicitly convert from void * to a pointer to function type, which would be needed for the code you have written to work. That argument to pthread_create is already the right type, there is no reason to cast it to something else.

Logan Capaldo
A: 

The problem is with the cast. You are casting the function pointer to a void* that can not be implicitly converted to (void (*)(void*) --which is the type accepted by pthread_create for the third argument.

You do not need to cast the argument as it is of the exact type, but if you had to, it would be:

void LaunchMemberFunction( Server * ); // signature now does not match, cast required:

static_cast<void (*)(void*)>(LaunchMemberFunction)
// or with C casts:
(void (*)(void*))LaunchMemberFunction
David Rodríguez - dribeas