Callback (computer programming)
In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back the argument at a given time. This execution may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback.
Programming languages support callbacks in different ways, often implementing them with subroutines, lambda expressions, blocks, or function pointers.
DesignThere are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks and deferred callbacks. While blocking callbacks are invoked before a function returns, deferred callbacks may be invoked after a function returns. Deferred callbacks are often used in the context of I/O operations or event handling, and are called by interrupts or by a different thread in case of multiple threads. Due to their nature, blocking callbacks can work without interrupts or multiple threads, meaning that blocking callbacks are not commonly used for synchronization or delegating work to another thread.
Callbacks are used to program applications in windowing systems. In this case, the application supplies a specific custom callback function for the operating system to call, which then calls this application-specific function in response to events like mouse clicks or key presses. A major concern here is the management of privilege and security: whilst the function is called from the operating system, it should not run with the same privilege as the system. A solution to this problem is using rings of protection.
ImplementationThe form of a callback varies among programming languages:
- In assembly, C, C++, Pascal, Modula2 and similar languages, a machine-level pointer to a function may be passed as an argument to another function. This is supported by most compilers and provides the advantage of using different languages together without special wrapper libraries or classes. One example may be the Windows API that is directly accessible by many different languages, compilers and assemblers.
- C++ allows objects to provide their own implementation of the function call operation. The Standard Template Library accepts these objects, as well as function pointers, as parameters to various polymorphic algorithms.
- CLI languages such as C# and VB.NET provide a type-safe encapsulating reference, a "delegate", to define well-typed function pointers. These can be used as callbacks.
- Events and event handlers, as used in.NET languages, provide generalized syntax for callbacks.
- Functional languages generally support first-class functions, which can be passed as callbacks to other functions, stored as data or returned from functions.
- Some languages, such as Algol 68, Perl, Python, Ruby, Smalltalk, C++11 and later, newer versions of C# and VB.NET as well as most functional languages, allow unnamed blocks of code to be supplied instead of references to functions defined elsewhere.
- In object-oriented programming languages without function-valued arguments, such as in Java before its 8 version, callbacks can be simulated by passing an instance of an abstract class or interface, of which the receiver will call one or more methods, while the calling end provides a concrete implementation. Such objects are effectively a bundle of callbacks, plus the data they need to manipulate. They are useful in implementing various design patterns such as Visitor, Observer, and Strategy.
CCallbacks have a wide variety of uses, for example in error signaling: a Unix program might not want to terminate immediately when it receives SIGTERM, so to make sure that its termination is handled properly, it would register the cleanup function as a callback. Callbacks may also be used to control whether a function acts or not: Xlib allows custom predicates to be specified to determine whether a program wishes to handle an event.
The following C code demonstrates the use of callbacks to display two numbers.
/* A possible callback */
/* Another possible callback. */
/* Here we call PrintTwoNumbers with three different callbacks. */
This should provide output similar to:
125185 and 89187225
9084 and 9441
42 and 42
Note how this is different from simply passing the output of the callback function to the calling function, PrintTwoNumbers - rather than printing the same value twice, the PrintTwoNumbers calls the callback as many times as it requires. This is one of the two main advantages of callbacks.
The other advantage is that the calling function can pass whatever parameters it wishes to the called functions. This allows correct information hiding: the code that passes a callback to a calling function does not need to know the parameter values that will be passed to the function. If it only passed the return value, then the parameters would need to be exposed publicly.
* This is a simple C program to demonstrate the usage of callbacks
* The callback function is in the same file as the calling code.
* The callback function can later be put into external library like
* e.g. a shared object to increase flexibility.
* Prototype declaration
The output after compilation:
$ gcc cbtest.c
App Id = 100
Msg = This is a test
This information hiding means that callbacks can be used when communicating between processes or threads, or through serialised communications and tabular data.
C#A simple callback in C#:
public class Class1
public class Class2
// alerts 75, the product of 5 and 15
// alerts 20, the sum of 5 and 15
First a function is defined with a parameter intended for callback:. Then a function that can be used as a callback to is defined,. Other functions may be used for, like. In this example, is invoked twice, once with as a callback and once with. The functions return the product and sum, respectively, and then the alert will display them to the screen.
- return is implied as the code in each function is the last line of the block
- As alert requires a string, form produces a string from the result of calculate
- The get-word! values trigger the interpreter to return the code of the function rather than evaluate with the function.
- The datatype! references in a block! restrict the type of values passed as arguments.
num1 + num2
; alerts 75, the product of 5 and 15
alert form calculate 5 15 :calc-product
; alerts 20, the sum of 5 and 15
alert form calculate 5 15 :calc-sum
LuaA color tweening example using the [Roblox engine that takes an optional.done callback:
local DT = wait
local step_r = finish_color.r - object.BackgroundColor3.r
local step_g = finish_color.g - object.BackgroundColor3.g
local step_b = finish_color.b - object.BackgroundColor3.b
local total_steps = 1/
for i = 0, 1, DT* do
object.BackgroundColor3 = Color3.new,
if completed then
print "Color tweening finished!"
PythonA classic use of callbacks in Python is to assign events to UI elements.
Here is a very trivial example of the use of a callback in Python. First define two functions, the callback and the calling code,
then pass the callback function into the calling code.
>>> def get_square:
... """The callback."""
... return val ** 2
>>> def caller:
... return func