How to pass a pointer to a member function to a C function?

user1115652 picture user1115652 · Jun 24, 2010 · Viewed 9.1k times · Source

Possible Duplicate:
Using a C++ class member function as a C callback function

I'm writing an object-oriented library using a C library (winpcap). I need to pass the callback function that is called when a network packet arrives as a function pointer. I would like to pass a member function pointer to winpcap, to keep my design object oriented and to allow for different objects to receive different packets. However member functions as far as I understand have a different calling convention, and thus cannot be passed to a C function. Is there a way to fix this. My experiments with boost::bind (which I hardly manage to use other than trial and error) are not fruitful.

Is there a way to change the calling convention of a member function?

This is the definition of the callback function I use now and the actual passing of it to winpcap

void pcapCallback( byte* param, const struct pcap_pkthdr* header, const byte* pkt_data );

pcap_loop( adhandle, 0, pcapCallback, NULL );

The pcap_loop just takes the name of the function (which is on the global scope at the moment). This is the definition of the function pointer parameter (3rd parameter of pcap_loop). Since this is third party code I can't really change this. I would have to have a member function that can take this form:

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

As far as I understand it, the member function will be using thiscall and the c function pointer wants a cdecl

Answer

Pardeep picture Pardeep · Jun 24, 2010

Kindly refer to detailed topic about

How to Implement a Callback to a static C++ Member Function ?

How to Implement a Callback to a non-static C++ Member Function ?

http://www.newty.de/fpt/callback.html