Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D: Delegates or callbacks?

I found conception of Delegates pretty hard for me. I really do not understand why I can't simply pass one function to another and need to wrap it to Delegate. I read in docs that there is some cases when I do not know it's name and Delegate is only way to call it.

But now I have trouble in understanding conception of callbacks. I tried to find more information, but I can't understand is it's simply call of other function or what is it.

Could you show examples of D callbacks and explain where they can be helpful?

import vibe.d;

shared static this()
{
    auto settings = new HTTPServerSettings;
    settings.port = 8080;

    listenHTTP(settings, &handleRequest);
}

void handleRequest(HTTPServerRequest req,
                   HTTPServerResponse res)
{
    if (req.path == "/")
        res.writeBody("Hello, World!", "text/plain");
}

&handleRequest is it callback? How it's work and at what moment it's start?

like image 768
Dmitry Bubnenkov Avatar asked Mar 15 '23 09:03

Dmitry Bubnenkov


1 Answers

So within memory a function is just a pile of bytes. Like an array, you can take a pointer to it. This is a function pointer. It has a type of RETT function(ARGST) in D. Where RETT is the return type and ARGST are the argument types. Of course attributes can be applied like any function declaration.

Now delegates are a function pointer with a context pointer. A context pointer can be anything from a single integer (argument), call frame (function inside of another) or lastly a class/struct.

A delegate is very similar to a function pointer type at RETT delegate(ARGST). They are not interchangeable, but you can turn a function pointer into a delegate pointer pretty easily.

The concept of a callback is to say, hey I know you will know about X so when that happens please tell me about X by calling this function/delegate.

To answer your question about &handleRequest, yes it is a callback.

like image 184
Richard Andrew Cattermole Avatar answered Mar 20 '23 16:03

Richard Andrew Cattermole