lundi 21 octobre 2019

How to pass function pointer (callback) and call it without knowing it's type?

I have a function pointer as a member to a pure virtual base class. I'd like to pass this pointer to a library which does not know about either of these classes, MyBase or MyClass, and then call the function pointer as a callback into MyClass. I'm writing the lib as well. I want the shared library to call a callback in MyClass.

My question is, how does one pass a function pointer as an argument to a function and have it called without knowing anything about the class itself.

I was considering a pointer to a function pointer, but wasn't sure how to cast properly.

class MyBase {
    public:
        virtual void callback() = 0;
        void (MyBase::*callback_ptr)();
};

class MyClass : public MyBase {
    public:
        MyClass();
        void callback() { cout << "callback called" << endl; };
};

main.cpp

{
    MyClass my_class;
    my_class->callback_ptr = &MyBase::callback;

    lib->set_callback(my_class->callback_ptr);
}

lib.cpp

class MyLib {
    public:
        // how to declare the member function pointer here?
        void** callback_ptr;

        // how to write sig here?
        set_callback(ptr) { callback_ptr = ptr }

        running() {  
            // how to call the callback here w/o knowing it's type?
        }
}

Aucun commentaire:

Enregistrer un commentaire