2

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.

user1027524
  • 141
  • 2
  • 7
  • `Capture::capturar()` isn't static. If it was it would probably work, but isn't required to work. – Flexo Apr 01 '12 at 23:37
  • possible duplicate of [Using a C++ class member function as a C callback function](http://stackoverflow.com/questions/1000663/using-a-c-class-member-function-as-a-c-callback-function) – Flexo Apr 01 '12 at 23:39

2 Answers2

2

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.

David Schwartz
  • 166,415
  • 16
  • 184
  • 259
1

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.

Andrew Tomazos
  • 58,923
  • 32
  • 156
  • 267