Callback concept and normal calling - c++

I'm so confused
we know that all functions defined as global so we can call and use any function inside any block without passing it as argument
why we use Function callback concept while we can use a function inside any function without passing it
so why we use callback concept ?

For the same reason you use variables instead of constants.
Passing a callback to a function allow that function to call a different callback depending on how it was called.
Calling a function by name inside a function will always call that one function.

The call back concept means to provide some other function with a function to call when it needs something to be done, e.g. when an event happens. It also often means we can change the function to be called in run-time.
In this way, the knowledge of when to call what is not needed by the calling function. For example, a 3rd party library defines callbacks for the user's program to "plug-in" functionality into the library, or to be called when an event occurrs, a state is reached or an error occurrs and the library needs to know what to do about the error.
This is just a simple answer. Google around to find more information and see https://en.wikipedia.org/wiki/Callback_(computer_programming)

Related

Why to use function pointer? [duplicate]

This question already has answers here:
What is the point of function pointers?
(18 answers)
Closed 4 years ago.
I hope its an extremely repetitive question. And my advance excuse to all the viewers who find it annoying.
Although I am bit experienced programmer, but I cannot justify the use of function pointer over direct call. Scenarios where I unable to find the differences are -
1) callbacks - same can be achieved by direct call.
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
I really appreciate if someone can explain me using above scenarios with practical and really simple realistic example.
Some more things function pointers are often used for:
Runtime polymorphism: You can define a structure that encapsulates a function pointer, or a pointer to a function table. This enables you to call the specified function at runtime, even for a type of client object that did not exist when your library was written. You can use this to implement multiple dispatch or something like the visitor design pattern in C. This is also how C++ classes and their virtual member functions were originally implemented under the hood.
Closures: These can be structures containing a function pointer and one or more of its arguments.
State Machines: Instead of a switch with a case for each state label, I’ve often found it convenient to give the handler for each state its own function. The current state is the function you’re in, the state transitions are tail-recursive calls, and the program variables are parameters. The state labels then become function pointers, which you might store in a table or return from a function.
Higher-Order Functions: Two examples from the C standard library are qsort() and btree(), which generalize the type of elements and the comparison function.
Low-Level Support: Shared-library loaders, for example, need this.
1) callbacks - same can be achieved by direct call.
Not true. For a direct call, the caller must know the function name and signature when the code is compiled, and can only ever call that one function. A callback is defined at runtime and can be changed dynamically, while the caller need only know the signature, not the name. Moreover each instance of an object may have a different callback, whereas with a direct call, all instances must call the same function.
2) Asynchronous or synchronous event handling - anyway event has to be
identified, based on which element no. in function pointer array got
updated. But the same can be also done via direct call.
Not sure what you mean, but an event handler is simply a kind of callback. The event may be identified by the caller and different call-back handlers called through pointers. Your point only stands if there is one event handler for all event types and the user is to be responsible for identification.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
See (1) and (2) above. Often it is a means to hook platform independent third-party library code into a specific platform without having to deliver source-code or for system events that require user/application-defined handlers.
I would not sweat it however - if all your application requirements can be resolved without using a pointer to a function, then you don't need a pointer to a function. When you need one, you will probably know. You will most likely encounter it when you have to use an API that requires it before you ever implement an interface yourself that does. For example in the standard library the qsort() function requires a pointer to a function in order to define how two objects of arbitrary type are to be ordered - allowing qsort() to support any type of object - it is a way in C of making a function "polymorphic". C++ supports polymorphism directly, so there is often less need for explicit function-pointers in C++ - although internally polymorphism is implemented using function pointers in any case.
There is a concept in programming called DRY -- don't repeat yourself.
Suppose you have 121 buttons in your UI. Each one of them behaves much the same, except when you press the button, a different operation happens.
You can (A) use virtual inheritance to dispatch to the right operation (requiring a class per button), or (B) use a function pointer (or a std::function) stored in the class in order to call the right "on click" handler, or (C) have every single button be a distinct type.
A virtual function is implemented in every compiler I have examined as a complex table that, in the end, is a collection of function pointers.
So your choices are function pointers or generating 121 completely distinct buttons that happen to mostly behave the same.
In any situation where you want to decouple the caller and the called, you must use something akin to a function pointer. There are a ridiculous number of cases, from work queues to thread off tasks, callbacks, etc.
In tiny programs where everything is hard coded, hard coding every call can work. But hard coded stuff like this doesn't scale. When you want to update those 121 buttons each hand-implemented, knowing their points of customization is going to be ridiculously difficult. And they will fall out of sync.
And 121 is a modest number of buttons. What about an app with 10,000? And you want to update every button's behavior to handle touch-based input?
Even more, when you type erase, you can reduce binary size significantly. 121 copies of a class implementing a button is going to take more executable space than 1 class, each of which stores a function pointer or two.
Function pointers are but one type of "type erasure". Type erasure reduces binary size, provides clearer contracts between provider and consumer, and makes it easier to refactor behavior around the type erased data.
Without function pointers, how would you implement a function which calculates the integral of any real-valued function?
typedef double (*Function)(double);
double Integral(Function f, double a, double b);
1) callbacks - same can be achieved by direct call.
Not in all cases, since the caller may not know at compile-time what function must be called. For instance, this is typical in libraries since they cannot know in advance your code.
However, it can also happen in your own code: whenever you want to re-use partially a function, you can either:
Create several versions of that function, each calling a different function. Duplicates code, very bad maintenance. Good performance unless hit by code bloat.
Pass a function pointer (or callable in general in C++). Flexible, less code, performance might suffer in some cases.
Create a set of branches (if/switch chain), if you know in advance the set of possible functions to call. Rigid, but might be faster than a function pointer for small number of branches.
In C++, create a templated version. Same as the first case, but automated; so good maintenance. Code bloat might be an issue.
Factor out the common code so that callers can call whatever they need piece by piece. Sometimes this isn't possible/easy -- specially when parametrizing complex algorithms that you want to keep reusable (e.g. qsort()). In C++, see the STL (Standard Template Library).
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
Some event systems are designed so that you simply configure which function(s) will be triggered when a given event happens. If this is an external library with a C interface, they have no choice but to use function pointers.
Some other systems let you create your own event loop and you fetch the events somehow and do whatever you want with them; so they avoid callbacks.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
See the first case.
Thanks all for actively participating in this discussion. Thanks for giving practical examples like -
1) Implement Library function
2) Look qsort
3) Refer Linux Kernel
4) Generic Heap data structure in C
I feel qsort() void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) s is quite sufficient to clear my 1) & 3) point.
1) callbacks - same can be achieved by direct call.
3) In some post I had seen people commenting it is to be used when it is not known which function to call. I didn't get any proper justification for this.
Mainly by callbacks - it is a provision of calling a function for which the body is not yet defined. And it expected that the definition of the function will be provided later during run-time. So, compilation won't be hindered due to lack of function definition. Practical use if someone consider above qsort() function. In this the user is responsible for providing the function definition for compare() like -
int compare (int* a, int* b)
{
//User defined body based on problem requirement
}
Lets consider a practical scenario where multiple threads have their respective compare function. In case of direct call every thread need to implement their own sorting function or if a common function then implementation would be much more bulky. But by using the callback method all threads can use same function for sorting, since the sorting algo remain same for all threads.
Considering a layered architecture mainly higher layers have an abstract view of lower layer. So, here if say we have qsort() function [User defined qsort] implemented at application layer and lets say underlying application there is a ADC driver layer which capture sample and provide to application for sorting. Then for application it is not necessary to understand the definition of function responsible for collecting and providing the samples. But application will only focus on obtaining the sample. Hence, that main application won't know which function to call. Respective ADC driver will simply make a call to application using the qsort() and provide needful data.
Regarding 2 point still confused -
2) Asynchronous or synchronous event handling - anyway event has to be identified, based on which element no. in function pointer array got updated. But the same can be also done via direct call.
From above discussion I conclude that if event handlers pointed to some library function, then it need to be implemented via pointer to function. And secondly to create an independent and handy code it is necessary to maintain function pointer. Lets say between application and driver we have an interfacing layer. So, if either application or driver changes anytime it won't affect or very least affect each other. And this interface layer is implemented using pointer to function. But consider below scenario -
int (*fptr[10]) (void) =
{
function1; //function for starting LED
function2; //function for relay operation
.
.
function10; //function for motor control
}
lets say we have GPIO0.0 - GPIO0.10 has been mapped to the function pointer array. i.e. GPIO0.0 - 0th element of fptr
.
.
GPIO0.10 - 10th element of fptr
These GPIO pins has been configured for level triggered interrupt and their respective ISR will update the array element no. i=GPIO_Value; further the scheduler have an thread which will call the function pointer array -
fptr[i]();
Does the use of function pointer is justifiable here??

C Library Callback in C++ without pointer to "this"

I have a C library here which I want to wrap in a C++ class. The library works asynchronous and needs to set an error handler. I know how to wrap an error handler in a static class function for a C library, but I am used to having something like a void *user_data pointer, where I can put this in to call a member function from the static thunk.
Is there a way to register the callback for a member function directly, as this library does not feature a pointer to some userdata?
You can wrap it in your own static function which is aware of some global (or static local) object on which it is to operate. You can even make this function a static method if want, but you can't call a method on an object without supplying an object on which it is to be called.
Edit : having thought about it for a while, maybe there is a way. You can essentially emulate thread-local storage by having a global collection of collections of states indexed by thread id. Within each thread-bound collection of states you can keep a stack/queue (depending on how the data are processed) of calling objects. The callback can look up the stored queue (because the callback knows the thread id in which it is running). This would allow you to force a single-threaded framework to operate on multiple streams of data.

wxWidgets wxFileSystemHandler::OpenFile() never gets called

I extended the class wxFileSystemHandler to handle special protocols I use in my application. My implementation of wxFileSystemHandler::CanOpen() is called, recognizes the protocol and returns TRUE. But my implementation of wxFileSystemHandler::OpenFile() never gets called. I inspected the wxWidgets code and saw that the CanOpen() member function is called by the pointer that I registered. But when a call to OpenFile() is made they pass the pointer to a wxFileSystem::MakeLocal() member function that tries to get another pointer inside a hash map that, obviously, is not my instance.
Someone got a problem like this before?
Not sure what exactly are you doing, i.e. when do you expect your handler to be called, but in any case MakeLocal() is supposed to create a new instance of the same class if you mark the object as being dynamically creatable using wxRTTI macros and use the object as given otherwise. So if you really need the same object to be reused, you probably need to use wxDECLARE_ABSTRACT_CLASS() in its class. But OTOH why is it a problem to make a new instance?

Can (jni call) `DeleteLocalRef` be used on native function arguments

Ran into the ReferenceTable limit in my Android jni function. Cleaned it up with DeleteLocalRef, but I want to know if I should do the same for the arguments passed to the function from Java. Is it possible? If so, is it worthwhile?
Local references are created within a native method only. I dont think it is worthwhile doing that for the function arguments. Best practice will be to delete the local references if you are doing anything in a loop, or creating a lot. Take a look at sun's reference

C API function callbacks into C++ member function code

So, I'm using the FMOD api and it really is a C api.
Not that that's bad or anything. Its just it doesn't interface well with C++ code.
For example, using
FMOD_Channel_SetCallback( channel, callbackFunc ) ;
It wants a C-style function for callbackFunc, but I want to pass it a member function of a class.
I ended up using the Win32 trick for this, making the member function static. It then works as a callback into FMOD.
Now I have to hack apart my code to make some of the members static, just to account for FMOD's C-ness.
I wonder if its possible in FMOD or if there's a work around to link up the callback to a specific C++ object's instance member function (not a static function). It would be much smoother.
You cannot directly pass a member function. A member function has the implicit parameter this and C functions don't.
You'll need to create a trampoline (not sure the signature of the callback, so just doing something random here).
extern "C" int fmod_callback( ... args ...)
{
return object->member();
}
One issue is where does that object pointer come from. Hopefully, fmod gives you a generic context value that will be provided to you when your callback is made (you can then pass in the object pointer).
If not, you'll just need to make it a global to access it.
I guess it supposed to work like this:
You can assign some user data to channel by calling FMOD_Channel_SetUserData. This user data should be a pointer to your C++ object that handles events.
Then you should write C-style callback that extracts that object by calling FMOD_Channel_GetUserData and then calls your C++ instance method on that object.
There is a non-portable, and pretty hackish solution that has the advantage of at least being thread-safe, which the "trampoline" methods are not.
You can generate the actual function machine code on the fly. The basic idea is that you have a template for your call-back function that takes an object pointer and a member-function pointer and gives you a block of heap memory that you can pass to the library as a C call-back function, that will, when called, turn around and call the member function on that object.
It's messy, and you'll have to provide an implementation for any new platform (any time the calling convention changes), but it works, is thread-safe. (Of course you'll also have to watch out for DEP). The other thread-safe solution is to resort to thread-local storage (assuming that you know the call-back will happen on the same thread as the call you made).
See http://www.codeproject.com/KB/cpp/GenericThunks.aspx for an example of how you could go about generating thunks.
Using only a function pointer (and no additional separate object pointer) for a C callback is a broken design, in my humble opinion.
If the function were, instead, FMOD_Channel_SetCallback(channel, callbackFunc, callbackObj), then your static method just takes an instance of the object, then calls callbackObj->func() (which obviously can be non-static).
you need to use a trampoline and store the pointer to the object you want to get the member function called on in a global or static variable, i.e.
Object *x;
void callback_trampoline() { x->foobar(); }
...
FMOD_Channel_SetCallback(CHANNEL, callback_trampoline);