// Demonstrates calling a static member function through a plain C function pointer. #include #include extern "C" { typedef struct _p_Bar *Bar; struct _p_Bar { void *ctx; int (*fp)(int,void*); }; int BarSetCallback(Bar b,int (*fp)(int,void*),void *ctx) { b->fp = fp; b->ctx = ctx; return 0; } int BarCall(Bar b,int x) { return b->fp(x,b->ctx); } } class Foo { public: Foo(int x) : mystate(x) {}; int SetupBar(Bar b) { return BarSetCallback(b,this->Function,this); } static int Function(int a,void *ctx) { // No "this" in static functions, but "p" serves the same purpose here Foo *p = (Foo*)ctx; return a + p->mystate; } private: int mystate; }; int main(void) { Foo f1(1),f2(2); Bar b = (Bar)malloc(sizeof(*b)); // One way to set the callback BarSetCallback(b,f1.Function,&f1); printf("f1 10: %d\n",BarCall(b,10)); // A different way f2.SetupBar(b); printf("f2 20: %d\n",BarCall(b,20)); free(b); return 0; }