简体   繁体   中英

How to call C++ member function using typless Function Pointer

I am trying to create C++ Timer module and I am planning to pass a callback function to my API. In this way, a different module can register a callback and when a timeout occurred I could notify it. It is easy to do that in C with a simple function pointer but in C++ how can we pass a Member function of an existing instance. Because when timer calls to callback (member) method, I need to access members (this pointer).

There are lots of examples which know the type of to be called object but I am creating a generic module so I have no change to cast to exact type to a member.

I am not using C++11 so older version for a legacy embedded software.

My API could be

void (*TimerCallback)(void);

Timer::TimerCallback userCB;

Timer::Timer(TimerCallback cb) {
    userCB = cb;
}

void Timer::invoke() {
    userCB();
}

Let us assume I have a C++ class which needs a timer

class myModule {
private:
    Timer* timer;
    void timerCallbackFunc(void) { 
      count << "This " << this << endl; 
    }
public:
    myModule() {
        timer = new Timer(timerCallbackFunc);
    }
}

But I could not find any way to call the member function with owner's this pointer so cannot access to member fields.

Is there any way or any limitation in C++?

Thanks.

It seems you need something simple, not reinventing C++11 in C++03.

Therefore, consider the old C style callback where you pass a client code's state pointer to the callback. The client code can go like this:

timer = new Timer( timerCallback, this );

And in the callback (an ordinary namespace scope function, or static class member) it gets back the this argument as a void* that it must cast correctly, and then call the non- static member function.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM