user1027524
user1027524

Reputation: 151

Building error pcap_loop with libpcap and c++

Hi I'm using c++ and libpcap. When I try to call the function "mycallback" I get a building error. These are the function:

void Capture::mycallback (unsigned char * useless, const struct pcap_pkthdr *pkthdr, const unsigned char * packet){
[...]
}

and the call to the function:

void Capture::capturar(){
  [...]
  pcap_loop (descr, -1, mycallback, NULL);  //entramos en el bucle (infinito)
}

And this is the error:

error: argument of type 'void (Capture ::) (unsigned char *, const pcap_pkthdr *, const unsigned char *)' does not match '{aka pcap_handler void (*) (unsigned char *, const pcap_pkthdr *, const unsigned char *)} '

I don't understand the errors because the declaration is the same, can anyone help me?

Thanks.

Upvotes: 2

Views: 1861

Answers (2)

Andrew Tomazos
Andrew Tomazos

Reputation: 68588

Declare a seperate global function capture_callback_handler (or static class function):

void capture_callback_handler(unsigned char * user, const struct pcap_pkthdr *pkthdr, const unsigned char * packet)
{
    ((Capture*) user)->mycallback(user, pkthdr, packet);
}

and then call pcap_loop like this:

  Capture* pCapture = this;
  pcap_loop (descr, -1, capture_callback_handler, (u_char*) pCapture);

This is a standard C multi-instance "callback" pattern.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182743

Your call back is a class member function. On most platforms, you can use a static class member function, but ideally you should just use a regular function. If it needs special access to the class, you can make the function a friend of the class.

The error did make this clear:

... 'void (Capture ::) (unsigned char *, const pcap_pkthdr ... does not match '{aka pcap_handler void (*) (unsigned ...

Notice Capture :: appears on the left side of the 'does not match' and not on the right side? Whenever you get an error like this, compare the two sides and see what's different.

Upvotes: 2

Related Questions