I have this code:
void* ConfigurationHandler::sendThreadFunction(void* callbackData)
{
const EventData* eventData = (const EventData*)(callbackData);
//Do Something
return NULL;
}
void ConfigurationHandler::sendCancel()
{
EventData* eventData = new EventData();
eventData ->Name = "BLABLA"
pthread_t threadId = 0;
int ret = pthread_create(&threadId,
NULL,
ConfigurationHandler::sendThreadFunction,
(void*) eventData ); // args passed to thread function
if (ret)
{
log("Failed to launch thread!\n");
}
else
{
ret = pthread_detach(threadId);
}
}
I am getting a compiler error:
error: argument of type 'void* (ConfigurationHandler::)(void*)' does not match 'void* (*)(void*)'
You can't safely pass a C++ method - even a static method - as a routine to pthread_create
.
Assuming you don't pass an object - ie, ConfigurationHandler::sendThreadFunction
is declared as a static method:
// the following fn has 'C' linkage:
extern "C" {
void *ConfigurationHandler__fn (void *arg)
{
return ConfigurationHandler::sendThreadFunction(arg); // invoke C++ method.
}
}
And ConfigurationHandler__fn
would be passed as the argument to pthread_create
.
Typical approach to your problem is to pass C++ object to pthread_create() via void pointer (this data pointer in its interface). The thread function passed will be global (possible static function) which knows that the void pointer is actually an C++ object.
Like in this example:
void ConfigurationHandler::sendThreadFunction(EventData& eventData)
{
//Do Something
}
// added code to communicate with C interface
struct EvendDataAndObject {
EventData eventData;
ConfigurationHandler* handler;
};
void* sendThreadFunctionWrapper(void* callbackData)
{
EvendDataAndObject* realData = (EvendDataAndObject*)(callbackData);
//Do Something
realData->handler->sendThreadFunction(realData->eventData);
delete realData;
return NULL;
}
void ConfigurationHandler::sendCancel()
{
EvendDataAndObject* data = new EvendDataAndObject();
data->eventData.Name = "BLABLA";
data->handler = this; // !!!
pthread_t threadId = 0;
int ret = pthread_create(&threadId,
NULL,
sendThreadFunctionWrapper,
data );
if (ret)
{
log("Failed to launch thread!\n");
}
else
{
ret = pthread_detach(threadId);
}
}
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.