制作C风格的回调对象?

jma*_*erx 6 c++ liblacewing

我正在使用一个像这样回调的库:

void onReceive (Lacewing::Server &Server, Lacewing::Server::Client &Client,
                char * Data, int Size) {
  /* callback body */
}

Server.onReceive (onReceive); /* to register the handler */
Run Code Online (Sandbox Code Playgroud)

我希望能够将它包装在一个类中,该类可以决定在收到数据包(观察者模式)时要做什么.

我怎么能用C风格的回调做到这一点?该库未定义要继承的接口.

谢谢

Jam*_*lin 2

由于您使用的是 liblacewing,因此每个类都有一个void * Tag为用户数据提供的成员:

/* class method */

void MyServer::onReceive (Lacewing::Server &Server, Lacewing::Server::Client &Client,
            char * Data, int Size)
{
     /* callback body - this is inside the class */
}


/* global function wraps the class method */

void onReceive (Lacewing::Server &Server, Lacewing::Server::Client &Client,
            char * Data, int Size)
{
    ((MyServer *) Server.Tag)->onReceive (Server, Client, Data, Size);
}
Run Code Online (Sandbox Code Playgroud)

然后:

Server.Tag = myServerInstance; /* set the class instance pointer */
Server.onReceive (::onReceive); /* register the global function */
Run Code Online (Sandbox Code Playgroud)