简体   繁体   English

如何使用无类型函数指针调用C ++成员函数

[英]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. 我正在尝试创建C ++ Timer模块,并计划将回调函数传递给我的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. 在C中使用简单的函数指针很容易做到这一点,但是在C ++中,我们如何传递现有实例的Member函数。 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. 我没有使用C ++ 11这么旧的版本用于旧版嵌入式软件。

My API could be 我的API可能是

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 让我们假设我有一个需要计时器的C ++类

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. 但是我找不到用所有者的this指针调用成员函数的任何方法,因此无法访问成员字段。

Is there any way or any limitation in C++? C ++有什么方法或任何限制吗?

Thanks. 谢谢。

It seems you need something simple, not reinventing C++11 in C++03. 似乎您需要一些简单的东西,而不是在C ++ 03中重新发明C ++ 11。

Therefore, consider the old C style callback where you pass a client code's state pointer to the callback. 因此,请考虑使用旧的C样式回调,在该回调中您将客户端代码的状态指针传递给该回调。 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. 在回调(普通的命名空间作用域函数或static类成员)中,它以必须正确转换的void*获取this参数,然后调用非static成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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