Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Callback (computer programming)

From Wikipedia, the free encyclopedia
Function reference passed to and called by another function
For a discussion of callback with computer modems, seeCallback (telecommunications).
icon
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Callback" computer programming – news ·newspapers ·books ·scholar ·JSTOR
(September 2015) (Learn how and when to remove this message)
A callback is often back on the level of the original caller.

Incomputer programming, acallback is aprogramming pattern in which afunctionreference is passed from one context (consumer) to another (provider) such that the provider can call the function. If the function accessesstate orfunctionality of the consumer, then the call isback to the consumer – backwards compared to the normalflow of control in which a consumer calls a provider.

A function that accepts a callbackparameter may be designed to call back beforereturning to its caller. But, more typically, a callback reference is stored by the provider so that it can call the function later (asdeferred). If the provider invokes the callback on the samethread as the consumer, then the call isblocking, a.k.a.synchronous. If instead, the provider invokes the callback on a different thread, then the call isnon-blocking, a.k.a.asynchronous.

A callback can be likened to leaving instructions with a tailor for what to do when a suit is ready, such as calling a specific phone number or delivering it to a given address. These instructions represent a callback: a function provided in advance to be executed later, often by a different part of the system and not necessarily by the one that received it.

The difference between a general function reference and a callback can be subtle, and some use the terms interchangeably but distinction generally depends on programming intent. If the intent is like thetelephone callback – that the originalcalled party communicates back to the originalcaller – then it's a callback.

Use

[edit]

A blocking callback runs in theexecution context of the function that passes the callback. A deferred callback can run in a different context such as duringinterrupt or from athread. As such, a deferred callback can be used for synchronization and delegating work to another thread.

Event handling

[edit]

A callback can be used for event handling. Often, consuming code registers a callback for a particular type of event. When that event occurs, the callback is called. Callbacks are often used to program thegraphical user interface (GUI) of a program that runs in awindowing system. The application supplies a reference to a custom callback function for the windowing system to call. The windowing system calls this function to notify the application of events likemouse clicks andkey presses.

Asynchronous action

[edit]

A callback can be used to implement asynchronous processing.

A caller requests an action and provides a callback to be called when the action completes which might be long after the request is made.

Polymorphism

[edit]

A callback can be used to implementpolymorphism. In the following pseudocode,say_hi can take eitherwrite_status orwrite_error.

fromtypingimportCallabledefwrite_status(message:str)->None:write(stdout,message)defwrite_error(message:str)->None:write(stderr,message)defsay_hi(write:Callable[[str],None])->None:write("Hello world")

Implementation

[edit]

The callback technology is implemented differently byprogramming language.

Inassembly,C,C++,Pascal,Modula2 and other languages, a callback function is stored internally as afunction pointer. Using the same storage allows different languages to directly share callbacks without adesign-time or runtimeinteroperabilitylayer. For example, theWindows API is accessible via multiple languages, compilers and assemblers. C++ also allows objects to provide an implementation of the function call operation. TheStandard Template Library accepts these objects (calledfunctors) as parameters. Manydynamic languages, such asJavaScript,Lua,Python,Perl[1][2] andPHP, allow a function object to be passed.CLI languages such asC# andVB.NET provide atype-safe encapsulating function reference known asdelegate. Events andevent handlers, as used in .NET languages, provide for callbacks. Functional languages generally supportfirst-class functions, which can be passed as callbacks to other functions, stored as data or returned from functions.

Many languages, including Perl, Python,Ruby,Smalltalk,C++ (11+), C# and VB.NET (new versions) and most functional languages, supportlambda expressions, unnamed functions with inline syntax, that generally act as callbacks. In some languages, includingScheme,ML, JavaScript, Perl, Python, Smalltalk, PHP (since 5.3.0),[3] C++ (11+), Java (since 8),[4] and many others, a lambda can be aclosure, i.e. can access variables locally defined in the context in which the lambda is defined. In anobject-oriented programming language such asJava versions before function-valued arguments, the behavior of a callback can be achieved by passing an object that implements an interface. The methods of this object are callbacks. InPL/I andALGOL 60 a callback procedure may need to be able to access local variables in containing blocks, so it is called through anentry variable containing both the entry point and context information.[5]

Example code

[edit]

C

[edit]

Callbacks have a wide variety of uses, for example in error signaling: aUnix program might not want to terminate immediately when it receivesSIGTERM, so to make sure that its termination is handled properly, it would register the cleanup function as a callback.

#include<stdlib.h>#include<signal.h>#include<sys/types>#include<fcntl.h>structDataCollection{....}data;voidcleanupHandler(intsignum){intsaveFile=open("saveFile.dat",O_WRONLY|O_CREATO,S_IWUSR);write(saveFile,data,sizeofdata);close(saveFile);}intmain(void){signal(cleanupHandler,SIGTERM);doStuff();}

Another common use for callbacks in C is withStdlib functions used for sorting (qsort) and searching (lsearch, bsearch) where a comparator function is passed as an argument to the routine to determine the collation order.[6]

#include<stdio.h>#include<stdlib.h>structPerson{charname[20];intage;}people[1000];intcompareAges(structPerson*p1,structPerson*p2){returnp2->age-p1->age;}//Collattes people by age...qsort(nPeople,sizeof(structPerson),people,compareAges);...


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. In the followingC code, functionprintNumber() uses parametergetNumber as a blocking callback.printNumber() is called withgetAnswerToMostImportantQuestion() which acts as a callback function. When run the output is: "Value: 42".

#include<stdio.h>#include<stdlib.h>voidprintNumber(int(*getNumber)(void)){intval=getNumber();printf("Value: %d\n",val);}intgetAnswerToMostImportantQuestion(void){return42;}intmain(void){printNumber(getAnswerToMostImportantQuestion);return0;}

C++

[edit]

In C++,functors can be used in addition to function pointer. A functor is an object withoperator() defined. For example, the objects instd::views are functors. This is an example of using functors in C++:

importstd;classMyCallback{public:voidoperator()(intx){std::println("Callback called with value: {}",x);}};template<typenameCallback>voidperformOperation(inta,Callbackcallback){std::println("Performing operation on: {}",a);callback(a);}intmain(){MyCallbackcallback;intvalue=10;performOperation(value,callback);return0;}

std::function<R(Args...)> is a type-erased wrapper for any callable objects, introduced inC++11:

importstd;usingstd::function;voidperformOperation(inta,function<void(int)>callback){std::println("Performing operation on: {}",a);callback(a);}intmain(){intvalue=10;performOperation(value,[](intx)->void{std::println("Callback called with value: {}",x);});return0;}

C#

[edit]

In the followingC# code, methodHelper.Method uses parametercallback as a blocking callback.Helper.Method is called withLog which acts as a callback function. When run, the following is written to the console: "Callback was: Hello world".

publicclassMainClass{staticvoidMain(string[]args){Helperhelper=newHelper();helper.Method(Log);}staticvoidLog(stringstr){Console.WriteLine($"Callback was: {str}");}}publicclassHelper{publicvoidMethod(Action<string>callback){callback("Hello world");}}

JavaScript

[edit]

In the followingJavaScript code, functioncalculate uses parameteroperate as a blocking callback.calculate is called withmultiply and then withsum which act as callback functions.

functioncalculate(a,b,operate){returnoperate(a,b);}functionmultiply(a,b){returna*b;}functionsum(a,b){returna+b;}// outputs 20alert(calculate(10,2,multiply));// outputs 12alert(calculate(10,2,sum));

The collection method.each() of thejQuerylibrary uses the function passed to it as a blocking callback. It calls the callback for each item of the collection. For example:

$("li").each(function(index){console.log(index+": "+$(this).text());});

Deferred callbacks are commonly used for handling events from the user, the client and timers. Examples can be found inaddEventListener,Ajax andXMLHttpRequest.[7]

In addition to using callbacks in JavaScript source code, C functions that take a function are supported via js-ctypes.[8]

Julia

[edit]

In the followingJulia code, functioncalculate accepts a parameteroperate that is used as a blocking callback.calculate is called withsquare which acts as a callback function.

julia>square(val)=val^2square (generic function with 1 method)julia>calculate(operate,val)=operate(val)calculate (generic function with 1 method)julia>calculate(square,5)25

Kotlin

[edit]

In the followingKotlin code, functionaskAndAnswer uses parametergetAnswer as a blocking callback.askAndAnswer is called withgetAnswerToMostImportantQuestion which acts as a callback function. Running this will tell the user that the answer to their question is "42".

funmain(){print("Enter the most important question: ")valquestion=readLine()askAndAnswer(question,::getAnswerToMostImportantQuestion)}fungetAnswerToMostImportantQuestion():Int{return42}funaskAndAnswer(question:String?,getAnswer:()->Int){println("Question:$question")println("Answer:${getAnswer()}")}

Lua

[edit]

In thisLua code, functioncalculate accepts theoperation parameter which is used as a blocking callback.calculate is called with bothadd andmultiply, and then uses ananonymous function to divide.

functioncalculate(a,b,operation)returnoperation(a,b)endfunctionmultiply(a,b)returna*bendfunctionadd(a,b)returna+bendprint(calculate(10,20,multiply))-- outputs 200print(calculate(10,20,add))-- outputs 30-- an example of a callback using an anonymous functionprint(calculate(10,20,function(a,b)returna/b-- outputs 0.5end))

Python

[edit]

In the followingPython code, functioncalculate accepts a parameteroperate that is used as a blocking callback.calculate is called withsquare which acts as a callback function.

defsquare(val:int)->int:returnval**2defcalculate(operate:Callable[[int],int],val:int)->int:returnoperate(val)# prints: 25print(calculate(square,5))

Red and REBOL

[edit]

The followingREBOL/Red code demonstrates callback use.

  • 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.
Red[Title:"Callback example"]calculate:func[num1[number!]num2[number!]callback-function[function!]][callback-functionnum1num2]calc-product:func[num1[number!]num2[number!]][num1*num2]calc-sum:func[num1[number!]num2[number!]][num1+num2]; alerts 75, the product of 5 and 15alertformcalculate515:calc-product; alerts 20, the sum of 5 and 15alertformcalculate515:calc-sum

Rust

[edit]

Rust have theFn,FnMut andFnOnce traits.[9]

fncall_with_one<F>(func:F)->usizewhereF:Fn(usize)->usize{func(1)}letdouble=|x|x*2;assert_eq!(call_with_one(double),2);

See also

[edit]

References

[edit]
  1. ^"Perl Cookbook - 11.4. Taking References to Functions". 2 July 1999. Retrieved2008-03-03.
  2. ^"Advanced Perl Programming - 4.2 Using Subroutine References". 2 July 1999. Retrieved2008-03-03.
  3. ^"PHP Language Reference - Anonymous functions". Retrieved2011-06-08.
  4. ^"What's New in JDK 8".oracle.com.
  5. ^Belzer, Jack; Holzman, Albert G; Kent, Allen, eds. (1979).Encyclopedia of Computer Science and Technology: Volume 12. Marcel Dekker, inc. p. 164.ISBN 0-8247-2262-0. RetrievedJanuary 28, 2024.
  6. ^Prinz, Peter; Crawford, Tony (Dec 12, 2015).C in a Nutshell (2nd ed.). Sebastopal California:O'Reilly Media Inc. pp. 538–540,374–377.ISBN 978-1-491-90475-6.
  7. ^"Creating JavaScript callbacks in components". Archive.UDN Web Docs (Documentation page). sec. JavaScript functions as callbacks.Archived from the original on 2021-12-16. Retrieved2021-12-16.
  8. ^Holley, Bobby; Shepherd, Eric (eds.)."Declaring and Using Callbacks". Docs.Mozilla Developer Network (Documentation page).Archived from the original on 2019-01-17. Retrieved2021-12-16.
  9. ^"Fn in std::ops - Rust".doc.rust-lang.org. Retrieved18 January 2025.

External links

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Callback_(computer_programming)&oldid=1338449044"
Category:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp