简体   繁体   English

在C ++库中创建回调函数

[英]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). (如果可能,我希望避免将变量(例如函数指针)传递到库的选择)。

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. 希望能帮助到你。

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

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