Callback functions: what are they in computer programming languages?
I see a lot of callback functions in low-level API's like Win32. But I am confused on what a callback function or callback subroutine is. Is an event in c# considered a 开发者_开发问答callback function?
A callback function is a function that is passed to something else, which will later call the function to notify the user of something. This implies that there must be a way to pass a reference to a function to another, for instance a type of function pointer. In .NET, delegates are used.
An event handler method is an example of a callback function.
In .NET a delegate is the closest match to a Win32 API type callback, though a delegate is far more functional. Events themselves are based on underlying delegates.
The most common use for a callback in the Win32 API is to enumerate resource or something similar. For example the EnumChildWindows API will kick off the enumeration of all the child windows of a specific window and call your custom callback routine for each child window found. Within that callback you can perform any actions that are relevant to your requirement that relate to the specific child window, for example you might be trying to enumerate the windows to programatically find a specific window based on some custom criteria that relates to that window, and once you find the window you can force the termination of the enumeration by returning false
from the callback.
In .NET this pattern of using a callback is not required because a more formalized solution is available using the IEnumerable interface.
Callbacks are a specific case of continuations. To quote PFPL, ch 30:
[first class] continuations ... are ordinary values with an indefinite lifetime that can be passed and returned at will in a computation. Continuations never “expire”, and it is always sensible to reinstate a continuation without compromising safety. Thus continuations support unlimited “time travel” — we can go back to a previous point in the computation and then return to some point in its future, at will.
Why are continuations useful? Fundamentally, they are representations of the control state of a computation at a given point in time. Using continuations we can “checkpoint” the control state of a program, save it in a data structure, and return to it later
Thus callbacks are just yet another example of continuations. Their use for asynchronous event processing follows from the ability to restore execution to some state via the continuation.
Continuations are particularly easy to use in languages with first class functions, and higher-order functions.
References: Practical Foundations for Programming Languages, Robert Harper, 2011.
精彩评论