Callback (computer science)
   HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, a callback or callback function is any reference to executable code that is passed as an
argument An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialecti ...
to another piece of code; that code is expected to ''call back'' (execute) the callback function as part of its job. This execution may be immediate as in a synchronous callback, or it might happen at a later point in time as in an asynchronous callback.
Programming languages A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
support callbacks in different ways, often implementing them with
subroutines In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. Functions may ...
, lambda expressions, blocks, or
function pointers A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function poi ...
.


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 (as in the C example below), 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 for delegating work to another thread. Callbacks are used to program applications in
windowing systems In computing, a windowing system (or window system) is software that manages separately different parts of display screens. It is a type of graphical user interface (GUI) which implements the WIMP (windows, icons, menus, pointer) paradigm fo ...
. 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: while 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 language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s: * In assembly, C, C++,
Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Frenc ...
, 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 The Windows API, informally WinAPI, is Microsoft's core set of application programming interfaces (APIs) available in the Microsoft Windows operating systems. The name Windows API collectively refers to several different platform implementations th ...
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 JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
, Lua, Python,
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
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 pointer A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function poi ...
s. These can be used as callbacks. * Events and
event handlers In programming and software design, an event is an action or occurrence recognized by software, often originating asynchronously from the external environment, that may be handled by the software. Computer events can be generated or triggered ...
, as used in .NET languages, provide generalized syntax for callbacks. * Functional languages generally support
first-class functions In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from ...
, which can be passed as callbacks to other functions, stored as data or returned from functions. * Some languages, such as
Algol 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously d ...
, Perl, Python,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
,
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan ...
,
C++11 C11, C.XI, C-11 or C.11 may refer to: Transport * C-11 Fleetster, a 1920s American light transport aircraft for use of the United States Assistant Secretary of War * Fokker C.XI, a 1935 Dutch reconnaissance seaplane * LET C-11, a license-build ...
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 A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
, ML, JavaScript, Perl, Python, Smalltalk, PHP (since 5.3.0), C++11 and later, Java (since 8), 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 Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
languages without function-valued arguments, such as in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
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 ''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a forewo ...
such as
Visitor A visitor, in English and Welsh law and history, is an overseer of an autonomous ecclesiastical or eleemosynary institution, often a charitable institution set up for the perpetual distribution of the founder's alms and bounty, who can inter ...
,
Observer An observer is one who engages in observation or in watching an experiment. Observer may also refer to: Computer science and information theory * In information theory, any system which receives information from an object * State observer in co ...
, and
Strategy Strategy (from Greek στρατηγία ''stratēgia'', "art of troop leader; office of general, command, generalship") is a general plan to achieve one or more long-term or overall goals under conditions of uncertainty. In the sense of the " ...
.


Use


C

Callbacks have a wide variety of uses, for example in error signaling: a
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, ...
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. #include #include #include /* The calling function takes a single callback as a parameter. */ void PrintTwoNumbers(int (*numberSource)(void)) /* A possible callback */ int overNineThousand(void) /* Another possible callback. */ int meaningOfLife(void) /* Here we call PrintTwoNumbers() with three different callbacks. */ int main(void) Example output: and and 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 (not shown in the above example). This allows correct
information hiding In computer science, information hiding is the principle of segregation of the ''design decisions'' in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decisio ...
: 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: /* * 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. * */ #include #include typedef struct _MyMsg MyMsg; void myfunc(MyMsg *msg) /* * Prototype declaration */ void (*callback)(MyMsg *); int main(void) The output after compilation: $ gcc cbtest.c $ ./a.out 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. In C++,
functor In mathematics, specifically category theory, a functor is a mapping between categories. Functors were first considered in algebraic topology, where algebraic objects (such as the fundamental group) are associated to topological spaces, and m ...
is also commonly used beside the usage of function pointer in C.


C#

A simple callback in C#: public class Class1 public class Class2


Kotlin

A simple callback in Kotlin: fun main() fun meaningOfLife(): Int fun answer(question: String?, answer: () -> Int)


JavaScript

Callbacks are used in the implementation of languages such as
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
, including support of JavaScript functions as callbacks through js-ctypes and in components such as addEventListener. However, a native example of a callback can be written without any complex code: function calculate(num1, num2, callbackFunction) function calcProduct(num1, num2) function calcSum(num1, num2) // alerts 75, the product of 5 and 15 alert(calculate(5, 15, calcProduct)); // alerts 20, the sum of 5 and 15 alert(calculate(5, 15, calcSum)); 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. In this primitive example, the use of a callback is primarily a demonstration of principle. One could simply call the callbacks as regular functions, . 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 XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser's JavaScript environment. Particularly, retrieval of data from XHR for the purpos ...
requests. Useful examples can be found in
JavaScript libraries A JavaScript library is a library of pre-written JavaScript code that allows for easier development of JavaScript-based applications, especially for AJAX and other web-centric technologies. Libraries With the expanded demands for JavaScript, an ...
such as
jQuery jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax. It is free, open-source software using the permissive MIT License. As of Aug 2022, jQuery is u ...
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 JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
above, here is how one would implement the same in either REBOL or
Red (programming language) Red is a programming language designed to overcome the limitations of the programming language Rebol. Red was introduced in 2011 by Nenad Rakočević, and is both an imperative and functional programming language. Its syntax and general usage ov ...
. 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! loat! integer!restrict the type of values passed as arguments. Red itle: "Callback example" calculate: func ____num1_[number! ____num2_[number!.html" ;"title="umber!.html" ;"title=" num1 [number!"> num1 [number! num2 [number!">umber!.html" ;"title=" num1 [number!"> num1 [number! num2 [number! callback-function [function!] ][ callback-function num1 num2 ] calc-product: func ____num1_[number! ____num2_[number!.html" ;"title="umber!.html" ;"title=" num1 [number!"> num1 [number! num2 [number!">umber!.html" ;"title=" num1 [number!"> num1 umber! ____num2_[number! ____num1_*_num2 .html" ;"title="umber!.html" ;"title="umber! num2 [number!">umber! num2 [number! num1 * num2 ">umber!.html" ;"title="umber! num2 [number!">umber! num2 [number! num1 * num2 calc-sum: func ____num1_[number! ____num2_[number!.html" ;"title="umber!.html" ;"title=" num1 [number!"> num1 [number! num2 [number!">umber!.html" ;"title=" num1 [number!"> num1 umber! num2 [number! 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


Lua

A color tweening example using the
Roblox ''Roblox'' () is an online game platform and game creation system developed by Roblox Corporation that allows users to program games and play games created by other users. Created by David Baszucki and Erik Cassel in 2004 and released i ...
engine that takes an optional .done callback: wait(1) local DT = wait() function tween_color(object, finish_color, fade_time) 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/(DT*(1/fade_time)) local completed; coroutine.wrap(function() for i = 0, 1, DT*(1 / fade_time) do object.BackgroundColor3 = Color3.new ( object.BackgroundColor3.r + (step_r/total_steps), object.BackgroundColor3.g + (step_g/total_steps), object.BackgroundColor3.b + (step_b/total_steps) ) wait() end if completed then completed() end end)() return end tween_color(some_object, Color3.new(1, 0, 0), 1).done(function() print "Color tweening finished!" end)


Python

A typical 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. >>> def get_square(val): ... """The callback.""" ... return val ** 2 ... >>> def caller(func, val): ... return func(val) ... >>> caller(get_square, 5) 25


Julia

Functions in Julia are
first-class citizen In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include ...
, so they can simply be passed to higher-level functions to be used (called) within the body of that functions. Here the same example above in Julia: julia> get_square(val) = val^2 # The callback get_square (generic function with 1 method) julia> caller(func,val) = func(val) caller (generic function with 1 method) julia> caller(get_square,5) 25


See also

* Command pattern * Continuation-passing style *
Event loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
*
Event-driven programming In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or message passing from other programs or thr ...
*
Implicit invocation Implicit invocation is a term used by some authors for a style of software architecture in which a system is structured around event handling, using a form of callback. It is closely related to inversion of control and what is known informally a ...
*
Inversion of control In software engineering, inversion of control (IoC) is a design pattern in which custom-written portions of a computer program receive the flow of control from a generic framework. A software architecture with this design inverts control as co ...
*
libsigc++ libsigc++ is a C++ library for typesafe callbacks. libsigc++ implements a callback system for use in abstract interfaces and general programming. libsigc++ is one of the earliest implementations of the signals and slots concept implemented us ...
, a callback library for C++ * Signals and slots * User exit


References

{{reflist


External links


Basic Instincts: Implementing Callback Notifications Using Delegates



Implement Script Callback Framework in ASP.NET

Interfacing C++ member functions with C libraries
(archived from the original on July 6, 2011)

Articles with example C code Subroutines