C++ class member function callback

前端 未结 3 732
鱼传尺愫
鱼传尺愫 2020-12-03 13:07

I have the following problem. I have a function from an external library (which cannot be modified) like this:

void externalFunction(int n, void udf(double*)         


        
3条回答
  •  余生分开走
    2020-12-03 13:53

    This is impossible to do - in c++, you must use either a free function, or a static member function, or (in c++11) a lambda without capture to get a function pointer.

    GCC allows you to create nested function which could do what you want, but only in C. It uses so-called trampolines to do that (basically small pieces of dynamically generated code). It would be possible to use this feature, but only if you split some of the code calling externalFunction to a separate C module.

    Another possibility would be generating code at runtime eg. using libjit.

    So if you're fine with non-reenrant function, create a global/static variable which will point to this and use it in your static function.

    class myClass
    {
    public:
        static myClass* callback_this;
        static void classUDF(double* a)
        {
            callback_this.realUDF(a);
        };
    };
    

    Its really horrible code, but I'm afraid you're out of luck with such a bad design as your externalFunction.

提交回复
热议问题