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 に答える