1

我有这个代码:

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*)'
4

2 回答 2

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.

于 2012-12-06T19:47:03.297 回答
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);
    }   
}
于 2012-12-06T19:55:48.883 回答