Callback function
   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 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 instructions", as opposed to a data file ...
that is passed as an argument 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 Lambda expression may refer to: *Lambda expression in computer programming, also called an anonymous function, is a defined function not bound to an identifier. * Lambda expression in lambda calculus, a formal system in mathematical logic and ...
, 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 (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 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 Ring may refer to: * Ring (jewellery), a round band, usually made of metal, worn as ornamental jewelry * To make a sound with a bell, and the sound made by a bell :(hence) to initiate a telephone connection Arts, entertainment and media Film and ...
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 Assembly may refer to: Organisations and meetings * Deliberative assembly, a gathering of members who use parliamentary procedure for making decisions * General assembly, an official meeting of the members of an organization or of their representa ...
, C,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, Pascal,
Modula2 Modula-2 is a structured, procedural programming language developed between 1977 and 1985/8 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith personal workstation. It ...
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 The Standard Template Library (STL) is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called ''algorithms'', '' ...
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 Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
,
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 PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
, 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 Comm ...
such as C# and
VB.NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visua ...
provide a
type-safe In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that is ...
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 (Unit ...
", 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,
C++11 C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions b ...
and later, newer versions of C# and VB.NET as well as most functional languages, allow unnamed blocks of code (
lambda expressions Lambda expression may refer to: *Lambda expression in computer programming, also called an anonymous function, is a defined function not bound to an identifier. * Lambda expression in lambda calculus, a formal system in mathematical logic and ...
) 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 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 mos ...
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 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.


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, an ...
program might not want to terminate immediately when it receives
SIGTERM Signals are standardized messages sent to a running program to trigger specific behavior, such as quitting or error handling. They are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-comp ...
, 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 written in the C programming language. It contains functions for interacting with an X server. These functions allow programmers to write programs without knowing the ...
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 e ...
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 In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name ...
*
Continuation-passing style In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation. This is contrasted with direct style, which is the usual style of programming. Gerald Jay Suss ...
*
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++, a callback library for C++ *
Signals and slots Signals and slots is a language construct introduced in Qt for communication between objects which makes it easy to implement the observer pattern while avoiding boilerplate code. The concept is that GUI widgets can send signals containing event ...
*
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