[英]Callback to a member function
I have a callback with this signature (I'm using Live555): 我有一个带有此签名的回调(我正在使用Live555):
typedef void(RTSPClient::responseHandler)(RTSPClient*, ...); //... = other parameters
Then in my code I have created a subclass of RTSPClient following the library rules: 然后在我的代码中,按照库规则创建了RTSPClient的子类:
class MyRTSPClient: public RTSPClient {
...
//callback
void continueAfterDESCRIBE(RTSPClient *client, ...); //same signature of typedef
...
};
Now comes the problem. 现在出现了问题。
In my code I have to invoke the following method: 在我的代码中,我必须调用以下方法:
unsigned RTSPClient::sendDescribeCommand(responseHandler, ...); //response handler is the typedef
If I create an object: 如果我创建一个对象:
MyRTSPClient *client = MyRTSPClient::createNew(...); //is library requirement such creation
how can I pass the function object to sendDescribeCommand
as callback? 如何将函数对象传递给
sendDescribeCommand
作为回调?
Of course if I declare continueAfterDESCRIBE
as static member I haven't any problem, but I want an object because I have many threads and if I use a static callback called from them many problems of synchronization will be raised. 当然,如果我将
continueAfterDESCRIBE
声明为静态成员,我没有任何问题,但是我想要一个对象,因为我有很多线程,如果我使用从其调用的静态回调,则会引发许多同步问题。
So I'm struggling (as a newbie in C++) how to find out the correct signature to pass an obj->method
as a callback. 因此,我正在努力(作为C ++中的新手)如何找到正确的签名,以将
obj->method
作为回调传递。
You cannot use a non-static member function as a callback parameter that expects a regular function, because their signatures are incompatible: 您不能将非静态成员函数用作需要常规函数的回调参数,因为它们的签名不兼容:
The common workaround for this is possible only if the library that performs a callback lets you pass custom parameters with the callback registration. 仅当执行回调的库允许您通过回调注册传递自定义参数时,才有可能使用此通用解决方法。 This is usually done with a
void*
pointer, which you pass to the library when you register the callback, and then the library passes it back to you when it calls back the callback function. 通常使用
void*
指针完成此操作,您可以在注册回调时将其传递给库,然后当库回调回调函数时将其传递给您。
Here is how: 方法如下:
// This is the static function that you register for your callback
static void staticContinueAfterDESCRIBE(RTSPClient *client, ...) {
static_cast<MyRTSPClient*>(client)-> continueAfterDESCRIBE(client, ...);
}
Now that the function is static, you have no problem registering it as a callback. 现在,该函数是静态的,将其注册为回调没有问题。 Once the function gets the control, it casts
client
to your MyRTSPClient*
class, and performs the non-static callback. 一旦函数获得控件,它将
client
转换为MyRTSPClient*
类,并执行非静态回调。
You want two pointers, one to an object and one to the member function: 您需要两个指针,一个指向对象,一个指向成员函数:
void (RTSPClient::*mfptr) = &RTSPClient::continueAfterDESCRIBE;
and one to an object: 一个对象:
RTSPClient* p = new RTSPClient();
and then call it: 然后调用它:
p->*mfptr(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.