Man*_*iAm 3 c++ function-pointers
我正在尝试使用 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 type \xe2\x80\x98pcap_handler {aka void (*)(unsigned char*, const pcap_pkthdr*, const unsigned char*)}\xe2\x80\x99\nRun Code Online (Sandbox Code Playgroud)\n\n我在这里做错了什么?
\n\n编辑:我在这里找到了类似的帖子。
\n您的回调函数不能是成员函数(方法)。不要忘记成员函数总是有隐藏参数this。
您的回调函数必须是命名空间级函数或类的静态成员。
如果您想让您的对象可用于 CB 函数,您可以使用成员user(pcap_loop()回调函数的第一个成员的最后一个参数)和适当的类型转换来传递任意数据,在您的情况下,应为您用于捕获的对象。
下面的代码不完整且未经测试,但可能会给您一个想法。
class SniffEther {
private:
pcap_t *cap_handler;
char errbuf[PCAP_ERRBUF_SIZE];
/* capture-related data members (properties) */
public:
static friend void pkt_callback(u_char *user, const pcap_pkthdr *hdr, const u_char *bytes){
SniffEther *sniffer=reinterpret_cast<SniffEther *>(user);
/*
Process header and bytes.
You can call things like sniffer->somemethod(), and also
access sniffer->someproperty.
*/
}
// constructor
SniffEther(const char *if_name){
cap_handler=pcap_create(if_name, errbuf);
if(!cap_handler)
throw runtime_error(errbuf);
/* Set the many pcap_options (see pcap(3)). */
if(pcap_activate(cap_handler)!=0){
string error(pcap_geterr(cap_handler));
pcap_close(cap_handler);
throw runtime_error(error);
}
}
~SniffEther(){
if(cap_handler)
pcap_close(cap_handler);
}
void capture_loop(int pkt_count=-1){
if(
pcap_loop(
cap_handler, pkt_count, pkt_callback,
reinterpret_cast<u_char *>(this)
)==-1
)
throw runtime_error(pcap_geterr(cap_handler));
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3147 次 |
| 最近记录: |