我有这段代码:
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);
}
}
我收到编译错误:
error: argument of type 'void* (ConfigurationHandler::)(void*)' does not match 'void* (*)(void*)'
答案 0 :(得分:0)
你无法安全地将C ++方法 - 甚至是静态方法 - 作为pthread_create
的例程传递。
假设您没有传递对象 - 即ConfigurationHandler::sendThreadFunction
被声明为静态方法:
// the following fn has 'C' linkage:
extern "C" {
void *ConfigurationHandler__fn (void *arg)
{
return ConfigurationHandler::sendThreadFunction(arg); // invoke C++ method.
}
}
并且ConfigurationHandler__fn
将作为参数传递给pthread_create
。
答案 1 :(得分:0)
解决问题的典型方法是通过void指针(在其接口中使用此数据指针)将C ++对象传递给pthread_create()。传递的线程函数将是全局的(可能是静态函数),它知道void指针实际上是一个C ++对象。
就像这个例子一样:
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);
}
}