HOME

TheInfoList




In
computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, generating algorithms, Profilin ...
, a callback, also known as a "call-after" function, is any
executable code In computing, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, causes a computer "to perform indicated tasks according to encoded instruction (computer science), instructions" ...
that is passed as an
argument In logic Logic is an interdisciplinary field which studies truth and reasoning Reason is the capacity of consciously making sense of things, applying logic Logic (from Ancient Greek, Greek: grc, wikt:λογική, λογική, la ...
to other code; that other code 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 point in time as in an asynchronous callback.
Programming languages A programming language is a formal language comprising a set of Formal language#Words over an alphabet, strings that produce various kinds of Machine code, machine code output. Programming languages are one kind of computer language, and are us ...
support callbacks in different ways, often implementing them with
subroutines In computer programming, a subroutine is a sequence of Instruction (computer science), program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular Task (computing), task sho ...
,
lambda expressions Lambda calculus (also written as ''λ''-calculus) is a formal system A formal system is an abstract structure used for inferring theorems from axioms according to a set of rules. These rules, which are used for carrying out the inference of theor ...
, blocks, or
function pointers A function pointer, also called a subroutine pointer or procedure pointer, is a pointer (computer programming), pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. de ...
.


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 ), 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 Privilege may refer to: Arts and entertainment * ''Privilege'' (film), a 1967 film directed by Peter Watkins * ''Privilege'' (Ivor Cutler album), 1983 * ''Privilege'' (Television Personalities album), 1990 * ''Privilege (Abridged) ''Privile ...
as the system. A solution to this problem is using
rings Ring most commonly refers either to a hollow circular shape or to a high-pitched sound. It thus may refer to: *Ring (jewellery), a circular, decorative or symbolic ornament worn on fingers, toes, arm or neck Ring may also refer to: Sounds * Ri ...
of protection.


Implementation

The form of a callback varies among
programming language A programming language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (computer science), words whose symbol (formal), letters are taken from an alphabet (computer science) ...

programming language
s: * In
assembly Assembly may refer to: Organisations and meetings * Deliberative assembly A deliberative assembly is a gathering of members (of any kind of collective) who use parliamentary procedure Parliamentary procedure is the body of ethics, Procedural l ...
, C,
C++ C++ () is a general-purpose programming language In computer software, a general-purpose programming language is a programming language dedicated to a general-purpose, designed to be used for writing software in a wide variety of application ...

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, French ...
,
Modula2 Modula-2 is a structured, procedural programming language developed between 1977 and 1985 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith (computer), Lilith personal wo ...
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 interface In computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and exp ...
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 The Standard Template Library (STL) is a software library for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called ''algorithm of an algorithm (Euclid's algorithm) for calcu ...
accepts these objects (called ''
functors In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), mathematical structure, structure (algebra), space (geometry), and calculus, change (mathematical analysis, analysis). I ...
''), as well as function pointers, as parameters to various polymorphic algorithms. * Many dynamic languages, such as
JavaScript JavaScript (), often abbreviated JS, is a programming language A programming language is a formal language In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), ma ...

JavaScript
, Lua,
Python Python may refer to: * Pythonidae The Pythonidae, commonly known as pythons, are a family of nonvenomous snakes found in Africa, Asia, and Australia. Among its members are some of the largest snakes in the world. Ten genera and 42 species ...
,
Perl Perl is a family of two high-level High-level and low-level, as technical terms, are used to classify, describe and point to specific Objective (goal), goals of a systematic operation; and are applied in a wide range of contexts, such as, for ...
and
PHP PHP is a general-purpose scripting language A scripting language or script language is a programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various k ...

PHP
, simply allow a function object to be passed through. *
CLI languages CLI languages are computer programming languages that are used to produce libraries and programs that conform to the Common Language Infrastructure (CLI) specifications. With some notable exceptions, most CLI languages compile entirely to the Commo ...
such as C# and
VB.NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigm ...
provide a
type-safe In computer science, type safety is the extent to which a programming language discourages or prevents type errors. A type error is erroneous or undesirable program behaviour caused by a discrepancy between differing data types for the program's con ...
encapsulating reference, a "
delegate Delegate or delegates may refer to: * Delegate, New South Wales, a town in Australia * Delegate (CLI), a computer programming technique * Delegate (American politics), a representative in any of various political organizations * Delegate (United St ...
", 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 poin ...
s. 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 A ruby is a pink-ish red to blood-red colored gemstone A gemstone (also called a fine gem, jewel, precious stone, or semi-precious stone) is a piece of mineral In geology and mineralogy, a mineral or mineral species is, broadly spea ...
,
Smalltalk Smalltalk is an object-oriented programming, object-oriented, dynamically typed reflection (computer science), reflective programming language. Smalltalk was created as the language underpinning the "new world" of computing exemplified by "human ...

Smalltalk
,
C++11 C11, C.XI, C-11 or C.11 may refer to: Transport * C-11 Fleetster The Consolidated Model 17 Fleetster was a 1920s United States, American light transport monoplane aircraft built by the Consolidated Aircraft, Consolidated Aircraft Corporation. De ...
and later, newer versions of C# and VB.NET as well as most functional languages, allow unnamed blocks of code (
lambda expressions Lambda calculus (also written as ''λ''-calculus) is a formal system A formal system is an abstract structure used for inferring theorems from axioms according to a set of rules. These rules, which are used for carrying out the inference of theor ...
) to be supplied instead of references to functions defined elsewhere. * In some languages, e.g. Scheme, 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 Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mai ...
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 147.7 million people, Java is the world's List of ...
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 Software engineering is the systematic application of engineering Engineering is the use of scientific principles to design and build ...
such as
Visitor A visitor, in English and Welsh "English and Welsh" is J. R. R. Tolkien's inaugural O'Donnell Memorial Lecture of October 21, 1955. The lecture sheds light on Tolkien's conceptions of the connections of race, ethnicity, and language A ...
,
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 con ...
, and
Strategy Strategy (from Greek#REDIRECT Greek Greek may refer to: Greece Anything of, from, or related to Greece Greece ( el, Ελλάδα, , ), officially the Hellenic Republic, is a country located in Southeast Europe. Its population is approxim ...

Strategy
.


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 Multi-user software is computer software Software is a collection of Instruction (computer science), instructions that tell a computer how to work. This is in contrast t ...

Unix
program might not want to terminate immediately when it receives
SIGTERM Signals are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-compliant operating systems. A signal is an wikt:asynchronous, asynchronous notification sent to a Process (computing), process or ...
, 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 Xlib (also known as libX11) is an X Window System protocol client library (computer science), library written in the C (programming language), C programming language. It contains subroutine, functions for interacting with an X Server (computin ...
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 /* 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 Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of com ...
: 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 Mathematics (from Greek: ) includes the study of such topics as numbers ( and ), formulas and related structures (), shapes and spaces in which they are contained (), and quantities and their changes ( and ). There is no ge ...
is also commonly used beside the usage of function pointer in C.


C#

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


JavaScript

Callbacks are used in the implementation of languages such as
JavaScript JavaScript (), often abbreviated JS, is a programming language A programming language is a formal language In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), ma ...

JavaScript
, 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 computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithmic processes and development of both comp ...
requests. Useful examples can be found in
JavaScript libraries A JavaScript library is a library A library is a collection of materials, books or media that are easily accessible for use and not just for display purposes. It is responsible for housing updated information in order to meet the user's needs ...
such as
jQuery jQuery is a JavaScript library A JavaScript library is a library A library is a curated collection of sources of information and similar resources, made accessible to a defined community for reference or borrowing. It provides physical or ...

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 JavaScript (), often abbreviated JS, is a programming language A programming language is a formal language In mathematics Mathematics (from Ancient Greek, Greek: ) includes the study of such topics as quantity (number theory), ma ...

JavaScript
above, here is how one would implement the same in either
REBOL #REDIRECT Rebol Rebol ( ; historically REBOL) is a cross-platform data exchange language and a multi-paradigm programming language, multi-paradigm dynamic programming language designed by Carl Sassenrath for network communications and distributed ...
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 programming, imperative and functional programming language. Its syntax ...
. 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 A game is a structured form of play Play most commonly refers to: * Play (activity), an activity done for enjoyment * Play (theatre), a work of drama Play may refer also to: Computers and technology ...

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


See also

*
Command pattern In object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. ...

Command pattern
*
Continuation-passing styleIn functional programming, continuation-passing style (CPS) is a style of programming in which control flow, control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Ge ...
*
Event loop Event may refer to: Gatherings of people * Ceremony A ceremony (, ) is a unified ritual A ritual is a sequence of activities involving gestures, words, actions, or objects, performed according to a set sequence. Rituals may be prescribed ...
*
Event-driven programming In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, gene ...
* Implicit invocation *
Inversion of control In software engineering, inversion of control (IoC) is a programming principle. IoC inverts the flow of control as compared to traditional control flow. In IoC, custom-written portions of a computer program A computer program is a collection ...
* libsigc++, a callback library for C++ * Signals and slots *
User exit A user exit is a subroutine invoked by a software package for a predefined event in the execution of the package. In some cases the exit is specified by the installation when configuring the package while in other cases the users of the package can ...


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