Alternative to c++ static virtual methods

前端 未结 12 2183
深忆病人
深忆病人 2020-12-04 21:58

In C++ is not possible to declare a static virtual function, neither cast a non-static function to a C style function pointer.

Now, I have a plain ol\' C SDK that us

12条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 22:12

    Assuming that the C SDK allows you to pass it a void * to your data (and you should pass it your this pointer for the derived class:)

    class Base {
    
      public:
    
        void Initialize() { /* Pass /this/ and a pointer to myFuncAGate to your C SDK */ }
    
        virtual myFuncA()=0;
    
        // This is the method you pass to the C SDK:
        static myFuncAGate(void *user_data) {
            ((Base*)user_data)->myFuncA();
        }
    };
    
    
    class Derived1: public Base {
      public:
        virtual myFuncA() { ... } // This gets called by myFuncAGate()
    };
    

    If the C SDK doesn't allow you to pass a pointer to your data which is then passed back to you through the callbacks, then you'll have a really hard time doing this. Since you indicated in one of your comments that this is indeed the case, you're pretty much out of luck. I would suggest using simple functions as callbacks, or overloading the constructor and defining multiple static methods. You'll still have a hard time determining what's the proper object your methods are supposed to work with when your callbacks are invoked by the C code.

    If you post more details about the SDK it might be possible to give you more relevant suggestions, but in the general case, even with static methods, you need some way of obtaining a this pointer to work with.

提交回复
热议问题