[英]C++ virtual method pointer
Im writing a simple socket server in C++. 我用C ++编写了一个简单的套接字服务器。 I've already have some libs from C which fires callback when event read happens on socket.
我已经有一些来自C的库,这些事件在套接字上发生事件读取时触发回调。 I want client who will use that class will impement its own mechanims to handle those events.
我希望将使用该类的客户施加自己的机制来处理这些事件。 My base class is:
我的基类是:
class CBaseServer{
...
void monitorDataArrived(int fd);
virtual void monitorOnDataArrived(void *context, int fd) = 0;
}
in this class pointer to monitorOnDataArrived(void *context, int fd)
has to be passed to extarnal C function called AddClient(int mask, proc, fd)
whenever new socket will appear. 在此类中
AddClient(int mask, proc, fd)
每当出现新的套接字时AddClient(int mask, proc, fd)
都必须将指向monitorOnDataArrived(void *context, int fd)
指针传递给名为AddClient(int mask, proc, fd)
外部C函数。 proc
is defined as: proc
定义为:
typedef void(*proc)(void *context, int fd)
CBaseServer::monitorDataArrived(fd){
proc p = (void (*)(void*, int)&CBase::monitorOnDataArrived;
addClient(MASK_READ, p, fd);
}
now client is doing: 现在客户正在做:
class Reader : class CBase{
void monitorOnDataArrived(void *context, int fd) {
std::cout << "hey, data arrived"
}
}
My question is: im having compliation errors: undefined refernece to CBaseServer::monitorOnDataArrived(void *, int)
我的问题是:即时通讯有
undefined refernece to CBaseServer::monitorOnDataArrived(void *, int)
错误: undefined refernece to CBaseServer::monitorOnDataArrived(void *, int)
Is there any way to fix it ? 有什么办法可以解决?
regards J. 问候J.
You are misunderstanding the function pointers in C++. 您误解了C ++中的函数指针。
You cannot pass a member function to a C handler, since a member function has an additional implicit parameter (the "this" parameter). 您不能将成员函数传递给C处理程序,因为成员函数具有附加的隐式参数(“ this”参数)。
What is the solution? 解决办法是什么? The solution is to use static functions which will cast the void * context parameter into an instance of your base class, and then calling the virtual function:
解决方案是使用静态函数,这些函数会将void *上下文参数转换为基类的实例,然后调用虚函数:
class CBaseServer{
...
//Watch that the context parameter has been moved from the virtual to the other
//function, which is now also static.
static void monitorDataArrived(void *context, int fd);
virtual void monitorOnDataArrived(int fd) = 0;
}
The dispatching code would be as following: 调度代码如下:
void CBaseServer::monitorDataArrived(void *context, int fd){
CBaseServer * server=(CBaseServer*)context;
server->monitorOnDataArrived(fd);
}
And the registration code would be: 注册代码为:
class Reader : class CBase{
void monitorOnDataArrived(int fd) {
std::cout << "hey, data arrived"
}
}
....
Reader * theReader=new Reader();
//The instance theReader of type Reader must be passed to the registration function
//as the void * context parameter.
addClient(MASK_READ, &theReader);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.