Callback function

from Wikipedia, the free encyclopedia

A callback function ( English callback ) referred to in the computer science a function that another function, usually a ready-made library or operating system function as a parameter passed and is called by this under defined conditions with defined arguments. This procedure follows the design pattern of the inversion of control .

In most cases, the prefabricated function allows the transfer of a so-called user parameter lpParameter, which is passed on by it (along with other arguments) to the callback function so that the latter can both access and store data in the context of the original caller.

Callback in the same process

ProgramExecCallbackSimple-de.png

The picture shows a call to a routine in a different context (operating system call , different software module). A reference to the callback routine is passed to this call. The called routine can then call the callback routine in its course. The callback routine ultimately stores data that can be used in the further program sequence after the original call has returned. In the English literature this form is referred to as blocking callback or synchronous callback .

The advantage of this technology is that the access to the data is formulated in its own context and / or any program-related preparation can take place in the callback: The parameters and the call time are determined in the other software module, the determination of what is carried out in the callback, is up to the own software module.

This enables functions to be defined in general and the behavior to be determined exactly when the function is called by specifying the callback function. A callback function is often not given a name at all, but is defined as an anonymous function directly when it is called (see also lambda calculus ). Callback functions are used to create a loose coupling between individual components.

Callback from another thread

Callback with thread intercommunication.png

If a callback function is specified, it is up to the called function to decide when it executes the callback ( inversion of control ). It is possible that the callback will come from another thread at a later time . The picture opposite shows the principle. The assignment of the callback routine to its own context is the same as in the above scheme. Since the callback can take place in a different thread, the conditions for data consistency ( mutex ) must also be observed. In the English literature, this form is called deferred callback or asynchronous callback .

An example of this is the call SetTimer(hWnd, ident, milliseconds, callbackRoutine)in the Windows API. The call SetTimer(...)is a short operating system call that only initializes the timer in the operating system. It callbackRoutinewill only be called when the time has expired. This happens in a thread of the operating system regardless of the sequence after calling SetTimer(...). Any code can be executed in the callback routine to be provided. It should be noted, however, that the callback routine may only be brief and not blocking. Otherwise there is a risk that the entire operating system or at least the current process will block. Ultimately, the callback routine should actually only store data and not itself contain complex actions. In particular, an event instance can be generated and stored for event- oriented programming , which controls further processes.

Permanent callback routine

A callback routine can only apply to one call at a time. The callback routine can also be called several times in relation to the call until the associated action has ended, i.e. for a limited time.

But also the permanent assignment of a routine is sometimes referred to as a callback routine , for example ThreadProc callback function: When creating a thread via the Windows API, the thread function is specified as a callback function .

The assignment of an event handling routine , for example to an HTML element <button onclick="function()" />or to a widget within the programming of graphical user interfaces, follows the same scheme, but in this context is usually not referred to as a callback but as an event handler .

Simple callback function or object-oriented callback

The so-called callback functions in the Windows API are each simple C functions. The Windows API is provided as a C interface. In forums there are often questions about the possibility of assigning C ++ functions. It is necessary here to encapsulate the C ++ call in a C function that knows the data instance.

It is different in object-oriented approaches to a recall. Instead of specifying a function pointer, the reference to a data object is transferred for the callback. The data object must implement an interface intended for the callback . The interface then contains several possible callback functions in the table of virtual methods within the data instance and at the same time knows the data necessary for executing the callback. The basic scheme is exactly the same as shown in the above schemes.

Examples

We want to apply_towrite a function that applies any other function to a list of values ​​and returns a list of the results. An implementation in pseudocode :

function apply_to (rückruffunktion, werte):
    var ergebnis; // Liste für die Ergebnisse
    foreach w in werte do // für alle Werte ...
        e = rückruffunktion (w); // rufe die Rückruffunktion ...
        ergebnis[] = e;   // und hänge das Resultat an die Ergebnisliste an.
    end;
    return ergebnis;
end apply_to;

This function can now be used as follows:

function verdoppeln (wert): // dies ist eine Rückruffunktion
    return wert*2;
end verdoppeln;
function quadrat (wert): // dies ist eine andere Rückruffunktion
    return wert*wert;
end quadrat;
// Anwenden der Funktionen auf eine Liste:
werte = (1, 2, 3, 4);
doppelte_Werte   = apply_to(verdoppeln, werte); //ergibt (2, 4, 6, 8)
quadrierte_Werte = apply_to(quadrat, werte);    //ergibt (1, 4, 9, 16)

Or, shorter, in lambda notation :

werte = (1, 2, 3, 4);
doppelte_Werte   = apply_to(lambda x: x*2, werte); //ergibt (2, 4, 6, 8)
quadrierte_Werte = apply_to(lambda x: x*x, werte); //ergibt (1, 4, 9, 16)

JavaScript

Callbacks are used in implementing programming languages like JavaScript , including supporting JavaScript functions as callbacks via js-ctypes and in components like addEventListener.

In the following example, a function calculation is first defined with a parameter intended for the callback : callback function . Then a function is defined that can be used as a callback to the calculation: calculateSum . Other functions can be used for the callback function, e.g. B. calculateProduct . In this example compute (...) is called twice, once with computeSum as a callback and once with computeProduct . The functions return the sum or product of the, and the warning displays them on the screen.

function berechne(zahl1, zahl2, rueckruffunktion)
{
    return rueckruffunktion(zahl1, zahl2);
}

function berechneSumme(zahl1, zahl2)
{
    return zahl1 + zahl2;
}

function berechneProdukt(zahl1, zahl2)
{
    return zahl1 * zahl2;
}

// Gibt 20, die Summe von 5 and 15, aus
alert(berechne(5, 15, berechneSumme));

// Gibt 75, das Produkt von 5 und 15, aus
alert(berechne(5, 15, berechneProdukt));

C #

public class Hauptklasse 
{
    static void Main(string[] args)
    {
        Nebenklasse objekt = new Nebenklasse();
        
        // Ruft die Methode von Nebenklasse mit Rückruffunktion als Parameter auf
        objekt.Aufrufmethode(Rueckruffunktion);
    }
    
    // Diese Rückruffunktion gibt den im Rückruf angegebenen Text aus
    static void Rueckruffunktion(string text)
    {
        Console.WriteLine("Der Rückruf lautet:" + text);
    }
}

public class Nebenklasse
{
    // Diese Methode hat eine andere Methode als Parameter und ruft diese auf
    public void Aufrufmethode(Action<string> rueckruf)
    {
        // Ruft die Methode Rueckruffunktion in Hauptklasse mit der der angegebenen Textnachricht aus
        rueckruf("Ich komme sofort zurück.");
    }
}

See also

Web links

Individual evidence

  1. msdn.microsoft ...