C ++类的成员函数回调 [英] C++ class member function callback

查看:222
本文介绍了C ++类的成员函数回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题。我有一个外部库(不能修改)的函数,如下所示:

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*) );

我想作为udf函数传递给现有类的函数成员。请查看以下代码:

I would like to pass as the udf function above a function member of an existing class. Please look at the following code:

// External function (tipically from an external library)
void externalFunction(int n, void udf(double*) )
{
     // do something
}

// User Defined Function (UDF)
void myUDF(double* a)
{
      // do something
}

// Class containing the User Defined Function (UDF)
class myClass
{
public:
    void classUDF(double* a)
    {
        // do something...
    };
};

int main()
{
    int     n=1;

    // The UDF to be supplied is myUDF
    externalFunction(n, myUDF);

    // The UDF is the classUDF member function of a myClass object
    myClass myClassObj;
    externalFunction(n, myClassObj.classUDF);   // ERROR!!
}



我不能将classUDF成员函数声明为静态函数,因此最后一行上面的代码导致编译错误!

I cannot declare the classUDF member function as a static function, so the last line of the code above results in a compilation error!

推荐答案

这是不可能做到的 - 在c ++中,函数或静态成员函数,或者(在c ++ 11中)没有捕获的lambda来获取函数指针。

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允许创建嵌套函数做你想要的,但只在C。它使用所谓的蹦床来做(基本上是动态生成的代码的小块)。只有当你把一些调用 externalFunction 的代码拆分成一个单独的C模块时,才有可能使用这个功能。

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.

另一种可能性是在运行时生成代码。使用 libjit

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

因此,如果你对非重用函数很好,创建一个全局/静态变量,指向 this ,并在你的静态函数中使用它。 / p>

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);
    };
};

它真的很可怕的代码,但恐怕你运气不好的设计作为 externalFunction

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

这篇关于C ++类的成员函数回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆