Edward
Edward

Reputation: 235

Creating a Callback Function in a C++ Library

I want to create a library that holds multiple objects and takes care of them. However, if certain things happen to the objects then I want to be able to perform additional actions in the project that uses the library.

The following is a brief example of what I want to do:

// Library:
class LibraryClass {
    public:
        bool Init() { /* Blah. */ }
        void Shutdown() { /* Blah blah. */ }

        void Update() {
            for( int i( 0); i < m_objects.size(); ++i) {
                bool somethingHappened = m_objects[i].Update();

                if( somethingHappened)
                    CallBackFunctionToMainProject( &m_objects[i]);
            }
        }

    private:
        std::vector<Objects> m_objects;
};

// Project that uses the library:
class Program {
    public:
        void Run() {
            m_libClass = new LibraryClass();
            m_libClass.Init();

            while( true) {
                m_libClass.Update();
                OtherUpdateStuff();
            }

            m_libClass.Shutdown();
            delete m_libClass;
        }
    private:
        LibraryClass* m_libClass;
};


void CallBackFunctionToMainProject( Object* obj) {
    // Do stuff.
}

So as you can see, I want the library to call the function that's declared in the main project, however I also want it to not complain if the function hasn't been declared in the main project.

Is it possible for me to do this? And if so, how? (If possible, I'd like to avoid the option of passing variables through to the library, such as a function pointer).

Upvotes: 0

Views: 1590

Answers (1)

ap-osd
ap-osd

Reputation: 2834

There are possible options but will have to pass/set something to the library to callback on.

  1. Pass a function pointer from the main program (you've mentioned it).
  2. Define an interface class in the library, which the main program will implement and pass it to the library (more elegant).
  3. Register a function pointer or interface object some place where the library can access (just a level of indirection than passing directly)

Hope it helps.

Upvotes: 2

Related Questions