About Me

Hyderabad, Andhra Pradesh, India

Tuesday, June 28, 2011

Callbacks

In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

Usually the higher level code first calls a function within the lower level code passing to it a pointer or handle to another function. Then the lower level function in the course of executing may call the passed-in function any number of times to perform some subtask. Another option is that the lower level function registers the passed-in function as a handler that is to be called asynchronously by the lower level at a later time in reaction to something.


Read more:
http://wiki.answers.com/Q/What_are_callback_functions#ixzz1IeAl8MBR

A callback function is one that is not invoked explicitly by the programmer; rather the responsibility for its invocation is delegated to another function that receives the callback function’s reference and instructions as to when to run the callback function.

This an excellent quote from Wikipedia explaining callback

Think of it as an “In case of fire, break glass” subroutine. Many computer programs tend to be written such that they expect a certain set of possibilities at any given moment. If “Thing That Was Expected”, then “Do something”, otherwise, “Do something else.” is a common theme. However, there are many situations in which events (such as fire) could happen at any time. Rather than checking for them at each possible step (“Thing that was expected OR Things are on fire”), it is easier to have a system which detects a number of events, and will call the appropriate function upon said event (this also keeps us from having to write programs like “Thing that was expected OR Things are on fire OR Nuclear meltdown OR alien invasion OR the dead rising from the grave OR…etc., etc.) Instead, a callback routine is a sort of insurance policy. If zombies attack, call this function. If the user moves their mouse over an icon, call HighlightIcon, and so forth.


Example: The requirement was that his Perl script needed to call a C# function (say Analyze ()). The Analyze () function would typically take a long time to process, and the client needed to be updated regularly with the progress counter. This would be best solved using Callbacks.

Callback function and implementation

Callback functions are ideal for use in situations in which a task is performed repeatedly. Another common usage is with enumeration functions, such as EnumFontFamilies, EnumPrinters, and EnumWindows in the Win32 API. As the example in the next section demonstrates, the EnumWindows function enumerates through all existing windows on your computer, calling the callback function to perform a task on each window.

Implementing Callback Functions

A callback function is code within a managed application that helps an unmanaged DLL function complete a task. Calls to a callback function pass indirectly from a managed application, through a DLL function, and back to the managed implementation. Some of the many DLL functions called with platform invoke require a callback function in managed code to run properly. This topic describes the elements of a callback function, and how to implement and call one from managed code.

Callback Function Basis

To call most DLL functions from managed code, you create a managed definition of the function and then call it. The process is straightforward.

Using a DLL function that requires a callback function has some additional steps. First, you must determine whether the function requires a callback by looking at the documentation for the function. Next, you have to create the callback function in your managed application. Finally, you call the DLL function, passing a pointer to the callback function as an argument. The following illustration summarizes these steps.

Callback function and implementation

http://i.msdn.microsoft.com/dynimg/IC27161.gif

Callback functions are ideal for use in situations in which a task is performed repeatedly. Another common usage is with enumeration functions, such as EnumFontFamilies, EnumPrinters, and EnumWindows in the Win32 API. As the example in the next section demonstrates, the EnumWindows function enumerates through all existing windows on your computer, calling the callback function to perform a task on each window.

Implementing a Callback Function

The following process demonstrates how a managed application, using platform invoke, can print the handle value for each window on the local computer. Specifically, the example uses the EnumWindows function to step through the list of windows and a managed callback function (named CallBack) to print the value of the window handle.

To implement a Callback function

  1. Look at the signature for the EnumWindows function before going further with the implementation. EnumWindows has the following signature:

BOOL EnumWindows (WNDENUMPROC lpEnumFunc, LPARAM lParam)

One clue that this function requires a callback is the presence of the lpEnumFunc argument. It is common to see the lp (long pointer) prefix combined with the Func suffix in the name of arguments that take a pointer to a callback function. For documentation about Win32 functions, see the Microsoft Platform SDK.

  1. Create the managed callback function. The example declares a delegate type, called CallBack, which takes two arguments (hwnd and lparam). The first argument is a handle to the window; the second argument is application-defined. In this release, both arguments must be integers.

Callback functions generally return nonzero values to indicate success and zero to indicate failure. This example explicitly sets the return value to true to continue the enumeration.

  1. Create a delegate and pass it as an argument to the EnumWindows function. Platform invoke converts the delegate to a familiar callback format automatically.
  2. Ensure that the garbage collector does not reclaim the delegate before the callback function completes its work. When you pass a delegate as a parameter, or pass a delegate contained as a field in a structure, it remains uncollected for the duration of the call. So, as is the case in the following enumeration example, the callback function completes its work before the call returns and requires no additional action by the managed caller.

If, however, the callback function can be invoked after the call returns, the managed caller must take steps to ensure that the delegate remains uncollected until the callback function finishes. For detailed information about preventing garbage collection, see Interop Marshaling with Platform Invoke.

No comments:

Post a Comment