Everipedia Logo
Everipedia is now IQ.wiki - Join the IQ Brainlist and our Discord for early access to editing on the new platform and to participate in the beta testing.
Callback (computer programming)

Callback (computer programming)

In computer programming, a callback, also known as a "call-after"[1] function, is any executable code that is passed as an argument to other code that is expected to call back (execute) 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.

Design

There are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known as asynchronous callbacks). While blocking callbacks are invoked before a function returns (in the C example below, which illustrates a blocking callback, it is function main), 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 reference to) 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.

Implementation

The 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 (internal or external) 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 (more or less) 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 (called functors), as well as function pointers, as parameters to various polymorphic algorithms.

  • Many dynamic languages, such as JavaScript, Lua, Python, Perl[2][3] and PHP, simply allow a function object to be passed through.

  • 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 (lambda expressions) to be supplied instead of references to functions defined elsewhere.

  • In some languages, e.g. Scheme, ML, JavaScript, Perl, Smalltalk, PHP (since 5.3.0),[4] C++11 and later, Java (since 8),[5] and many others, such functions can be closures, i.e. they can access and modify variables locally defined in the context in which the function was defined. Note that Java cannot, however, modify the local variables in the enclosing scope.

  • 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.

Use

C

Callbacks 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.

This should provide output similar to:

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 (not shown in the above example). 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.

Another example:

The output after compilation:

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#:

JavaScript

Callbacks are used in the implementation of languages such as JavaScript, including support of JavaScript functions as callbacks through js-ctypes[6] and in components such as addEventListener.[7] However, a native example of a callback can be written without any complex code:

First a function calculate is defined with a parameter intended for callback: callbackFunction. Then a function that can be used as a callback to calculate is defined, calcProduct. Other functions may be used for callbackFunction, like calcSum. In this example, calculate() is invoked twice, once with calcProduct as a callback and once with calcSum. The functions return the product and sum, respectively, and then the alert will display them to the screen.

In this primitive example, the use of a callback is primarily a demonstration of principle. One could simply call the callbacks as regular functions, calcProduct(num1, num2). Callbacks are generally used when the function needs to perform events before the callback is executed, or when the function does not (or cannot) have meaningful return values to act on, as is the case for Asynchronous JavaScript (based on timers) or XMLHttpRequest requests. Useful examples can be found in JavaScript libraries such as jQuery where the .each() method iterates over an array-like object, the first argument being a callback that is performed on each iteration.

Red and REBOL

From the JavaScript above, here is how one would implement the same in either REBOL or Red (programming language). Notice the cleaner presentation of data as code.

  • 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 (i.e., :calc-product and :calc-sum) trigger the interpreter to return the code of the function rather than evaluate with the function.

  • The datatype! references in a block! [float! integer!] restrict the type of values passed as arguments.

Lua

A color tweening example using the Roblox engine that takes an optional .done callback:

Python

A classic use of callbacks in Python (and other languages) 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.

See also

  • Command pattern

  • Continuation-passing style

  • Event loop

  • Event-driven programming

  • Implicit invocation

  • Inversion of control

  • libsigc++, a callback library for C++

  • Signals and slots

  • User exit

References

[1]
Citation Linkstackoverflow.com"What is a callback function?". Stack Overflow. Retrieved 2018-05-16.
Sep 29, 2019, 3:42 AM
[2]
Citation Linkwww.unix.org.ua"Perl Cookbook - 11.4. Taking References to Functions". Retrieved 2008-03-03.
Sep 29, 2019, 3:42 AM
[3]
Citation Linkwww.unix.org.ua"Advanced Perl Programming - 4.2 Using Subroutine References". Retrieved 2008-03-03.
Sep 29, 2019, 3:42 AM
[4]
Citation Linksecure.php.net"PHP Language Reference - Anonymous functions". Retrieved 2011-06-08.
Sep 29, 2019, 3:42 AM
[5]
Citation Linkwww.oracle.com"What's New in JDK 8". oracle.com.
Sep 29, 2019, 3:42 AM
[6]
Citation Linkdeveloper.mozilla.org"Callbacks". Mozilla Developer Network. Retrieved 13 December 2012.
Sep 29, 2019, 3:42 AM
[7]
Citation Linkdeveloper.mozilla.org"Creating Javascript Callbacks in Components". Mozilla Developer Network. Retrieved 13 December 2012.
Sep 29, 2019, 3:42 AM
[8]
Citation Linkweb.archive.orgBasic Instincts: Implementing Callback Notifications Using Delegates
Sep 29, 2019, 3:42 AM
[9]
Citation Linkwww.javaworld.comImplement callback routines in Java
Sep 29, 2019, 3:42 AM
[10]
Citation Linkweb.archive.orgImplement Script Callback Framework in ASP.NET
Sep 29, 2019, 3:42 AM
[11]
Citation Linkweb.archive.orgInterfacing C++ member functions with C libraries
Sep 29, 2019, 3:42 AM
[12]
Citation Linkgotw.caStyle Case Study #2: Generic Callbacks
Sep 29, 2019, 3:42 AM
[13]
Citation Linkstackoverflow.com"What is a callback function?"
Sep 29, 2019, 3:42 AM
[14]
Citation Linkwww.unix.org.ua"Perl Cookbook - 11.4. Taking References to Functions"
Sep 29, 2019, 3:42 AM
[15]
Citation Linkwww.unix.org.ua"Advanced Perl Programming - 4.2 Using Subroutine References"
Sep 29, 2019, 3:42 AM
[16]
Citation Linksecure.php.net"PHP Language Reference - Anonymous functions"
Sep 29, 2019, 3:42 AM
[17]
Citation Linkwww.oracle.com"What's New in JDK 8"
Sep 29, 2019, 3:42 AM
[18]
Citation Linkdeveloper.mozilla.org"Callbacks"
Sep 29, 2019, 3:42 AM
[19]
Citation Linkdeveloper.mozilla.org"Creating Javascript Callbacks in Components"
Sep 29, 2019, 3:42 AM
[20]
Citation Linkweb.archive.orgBasic Instincts: Implementing Callback Notifications Using Delegates
Sep 29, 2019, 3:42 AM