Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a C++ member function as the callback function for a C framework

Tags:

c++

c

callback

There is a C library (which I cannot change) that supports a callback function of the type

void (*callback)(void *appContext, int eventid)

I want to set a C++ function as the callback.

Specifically I have following questions?

  1. Do I need to declare the callback function under "extern C" block?

  2. Does a member function need to be static to be the callback function? Is it possible to use a non-static member function? If yes, how? And when is it recommended to use a non-static member function?

  3. Does it matter if the function is a template function or not?

  4. Does a non-class C style function have any advantages over a class member function?

I am trying these variants on a old VC++ compiler, which does not support the latest C++ standard. But the code needs to be platform independent and should work on most C++ compilers. I want to know what is recommended practice with callbacks?

like image 526
Oak Bytes Avatar asked Jul 19 '11 15:07

Oak Bytes


People also ask

What is the use of callback function in C?

A callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time [Source : Wiki]. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function.

How are callbacks implemented in C?

Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event() and data pointers to a framework function watch_events() (for example). When an event happens, your function is called with your data and some event-specific data.

What is a callback function and when would we use it?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.


1 Answers

Does callback function need to be declared under extern "C"?

NO. extern "C" is necessary only when you are calling a C++ function directly, without the use of function pointers, from C. If function pointers are used, extern "C" is not required.

Can I use non-static member functions as a callback?

NO. Non-static member functions of class A have an implicit first parameter corresponding to this pointer.

Can I use static member functions as a callback?

YES, as long as signature matches with that of the callback.

Does it matter if the function is a template function or not?

NO, template function can be used as callbacks as long as the signature of the instantiated template matches with the callback.

like image 170
Oak Bytes Avatar answered Oct 11 '22 18:10

Oak Bytes