Search code examples
c++pointer-to-member

c++ pointer to a function as argument


I have a C++ API with a cThread class, and this method to create a thread:

void cThread::start(void(*a_function)(void), CThreadPriority a_level);

I've done a class and a init() method to launch a thread and an updateHaptics() method to be executed by the thread:

void EntryClass::init()
{
typedef void (EntryClass::*method)();
method p;
p = &EntryClass::updateHaptics;

// create a thread which starts the main haptics rendering loop
cThread* hapticsThread = new cThread();
hapticsThread->start(p, CTHREAD_PRIORITY_HAPTICS);
}

void EntryClass::updateHaptics(void)
{
    // ...  
}

My problem is to pass the updateHaptics() method as an argument to the cThread::start() method.

I've got this error:

1>EntryClass.cpp(55): error C2664: 'void chai3d::cThread::start(void (__cdecl *)(void *),const chai3d::CThreadPriority,void *)' : impossible de convertir l'argument 1 de 'method' en 'void (__cdecl *)(void)'

REM: I'm under Windows 8/Visual Studio


Solution

  • The signature you indicated

    void(*a_function)(void)
    

    is for a function, not for a class method. A static method will work too

    Note the difference with the typedef you used:

    void (EntryClass::*method)();
    

    The definition could be:

    class EntryClass {
    public:
    
      void init();
    
      static void updateHaptics(); // <--- NOTE the static
    };
    

    and your implementation

    void EntryClass::init()
    {
    typedef void (*method)(); // <---- NOTE THIS CHANGE
    method p;
    p = &EntryClass::updateHaptics;
    
    // create a thread which starts the main haptics rendering loop
    cThread* hapticsThread = new cThread();
    hapticsThread->start(p, CTHREAD_PRIORITY_HAPTICS);
    }
    
    void EntryClass::updateHaptics(void)
    {
        // ...  
    }