我有一个C库,需要注册回调函数来定制一些处理.回调函数的类型是int a(int *, int *).
我正在编写类似于以下内容的C++代码,并尝试将C++类函数注册为回调函数:
class A {
public:
A();
~A();
int e(int *k, int *j);
};
A::A()
{
register_with_library(e)
}
int
A::e(int *k, int *e)
{
return 0;
}
A::~A()
{
}
Run Code Online (Sandbox Code Playgroud)
编译器抛出以下错误:
In constructor 'A::A()',
error:
argument of type ‘int (A::)(int*, int*)’ does not match ‘int (*)(int*, int*)’.
Run Code Online (Sandbox Code Playgroud)
我的问题:
我尝试过各种各样的设计方法来解决这个问题,但我似乎无法做到这一点.
我需要公开一些静态函数来用作C lib的回调函数.但是,我希望实际的实现是非静态的,所以我可以使用虚函数并在基类中重用代码.如:
class Callbacks {
static void MyCallBack() { impl->MyCallBackImpl(); }
...
class CallbackImplBase {
virtual void MyCallBackImpl() = 0;
Run Code Online (Sandbox Code Playgroud)
但是我尝试解决这个问题(Singleton,让回调包含在实现者类中,等等).我最终陷入了死胡同(impl通常最终指向基类,而不是派生类).
我想知道它是否完全可能,或者我是否坚持创建某种辅助函数而不是使用继承?
我正在尝试使用 Linux 中 libpcab 库中的 pcap_loop 函数与此原型:
\n\nint pcap_loop(pcap_t *, int, pcap_handler, u_char *);\nRun Code Online (Sandbox Code Playgroud)\n\npcap_pkthdr 是一个函数指针:
\n\ntypedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *, const u_char *);\nRun Code Online (Sandbox Code Playgroud)\n\n在我的程序中,我在 SniffEthernet 类中定义了以下方法:
\n\nvoid SniffEthernet::got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);\nRun Code Online (Sandbox Code Playgroud)\n\n现在调用 pcap_loop 如下
\n\npcap_loop(handle, num_packets, this->got_packet, NULL);\nRun Code Online (Sandbox Code Playgroud)\n\n给我以下编译时错误:
\n\nSniffEthernet.cc:139:58: error: cannot convert \xe2\x80\x98VENTOS::SniffEthernet::got_packet\xe2\x80\x99 from type \xe2\x80\x98void (VENTOS::SniffEthernet::)(u_char*, const pcap_pkthdr*, const u_char*) {aka void (VENTOS::SniffEthernet::)(unsigned char*, const pcap_pkthdr*, const unsigned char*)}\xe2\x80\x99 to …Run Code Online (Sandbox Code Playgroud)