将私有方法类成员作为指向函数的指针传递

时间:2014-01-28 00:44:13

标签: c++ oop pointers callback libpcap

我在论坛中搜索过,我尝试了几种我在这里找到的解决方案,但都没有。 我的问题是,我需要传递一个类的私有成员作为指向函数参数的指针,所以我尝试将此方法设置为静态,但它不起作用,遵循代码。

  class monitor {
   public:
    monitor(device *dev);
    ...
    void exec();
    void end();
    virtual ~monitor();

   private:
    static pcap_handler process_packet(u_char *arg, const struct pcap_pkthdr* pkthdr,
                          const u_char * packet);
    static void thread_func(monitor *mon);
      device *dev;
        };

以及该方法的使用方式:

void monitor::exec() {
  std::thread t (monitor::thread_func, this);
}

void monitor::thread_func(monitor *mon) {
  pcap_loop(mon->dev->get_descr(), -1, monitor::process_packet, reinterpret_cast<u_char*>(mon)); // error in this line
}

pcap_handler monitor::process_packet(u_char *arg, const struct pcap_pkthdr* pkthdr,
                             const u_char * packet) {
  monitor *mon = reinterpret_cast<monitor*>(arg);

  ...
}

错误是:

error: invalid conversion from ‘void (* (*)(u_char*, const pcap_pkthdr*, const u_char*))(u_char*, const pcap_pkthdr*, const u_char*) {aka void (* (*)(unsigned char*, const pcap_pkthdr*, const unsigned char*))(unsigned char*, const pcap_pkthdr*, const unsigned char*)}’ to ‘pcap_handler {aka void (*)(unsigned char*, const pcap_pkthdr*, const unsigned char*)}’ [-fpermissive]

error: initializing argument 3 of ‘int pcap_loop(pcap_t*, int, pcap_handler, u_char*)’ [-fpermissive]

遵循libpcap函数原型的代码

typedef void (*pcap_handler)(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes);

int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user);

我尝试了其他帖子中解释的几个解决方案:

pthread in a class

Private member function that takes a pointer to a private member in the same class

C++: Calling member function via pointer

Function pointer to class member function problems

但这些帖子都没有解决我的问题,所以,有人提示吗?

...谢谢

1 个答案:

答案 0 :(得分:1)

process_packet是一个返回pcap_handler的函数。它不是pcap_handler

要将其设为pcap_handler,请将其行更改为:

static void process_packet(u_char *arg, const struct pcap_pkthdr* pkthdr,
                      const u_char * packet);