2

Possible Duplicate:
How can I pass a C++ member function to a C API as a parameter

Hi I have class with a C function expecting a call back as follows: void fun_c(void * (*ptr)(void *)).

Now I want to send C++ method to c function, can anyone tell me how to do this:

class ClassA{
  method1(){
    func(ClassA::func);
  }
  void * func(void * arg){
  }
}

Can anyone will this work.

Community
  • 1
  • 1
maheshgupta024
  • 7,657
  • 3
  • 20
  • 18
  • There's a few oddities in your example code that make it harder to follow - `method1()` doesn't have a return type but isn't a constructor/destructor. `func` in `method1` will be the same as `ClassA::func`, passing a function a pointer to itself is weird. The signature for `func` doesn't actually take a function pointer, it takes a `void*`, which isn't legal. – Flexo Oct 20 '11 at 15:52

2 Answers2

0

You can't do this with an instance function because the C code will not have an instance available or even the knowledge of what to do with one. You need to use a static function instead.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

Basically usually cases like these you can declare

 void MyCallBack( void* arg )
 {
    ClassA * p = static_cast<ClassA*> (arg);
    //Invoke any member functions of p as needed
    p->HandleCallBack();
 }

This is based on the assumption that the call back function calls you back with some data* pointer that you give it. And you pass this when you setup your call back

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • 1
    And technically it also needs `extern "C"`, although in practice C++ implementations do use the same calling convention for free C++ functions as for C functions. Sadly it seems in this case the C API is badly-designed, since `fun_c` doesn't take a data pointer, just the function pointer. So the questioner is out of luck. – Steve Jessop Oct 20 '11 at 15:48
  • sorry my mistake : class ClassA{ method1(){ func(ClassA::func); } void * func(void * arg){ } } – maheshgupta024 Oct 20 '11 at 16:30