Passing a function as an argument to another function : what is this sorcery ?

Rikki Cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 25 02:55:21 PDT 2014


On 25/05/2014 9:37 p.m., Derix wrote:
> Hello everyone,
>
> So I'm "Getting Started With Gtkd" [1] and the tuto includes this
> piece of code :
>
> ...
>
>         DrawingArea da = new DrawingArea(590, 200);
>         da.addOnDraw(&onDraw);
>         layout.put(da, 5, 30);
>
>         add(layout);  // Add the layout to our main window
>         showAll();
>      }
>
>      bool onDraw(Context c, Widget w)
>      {
>         //draw things
>         return true;
>      }
> }
>
> and I'm a bit puzzled by the line
>         da.addOnDraw(&onDraw);
>
> I'm pretty sure I've met this construct before along with
> relevant explainations, but I find myself a bit forgetful and in
> need of a refresher. Hence questions :
>
> 1) What is the generic name for this kind construct ?

In this case &onDraw is a pointer to a member function aka delegate.
There is two types of pointers for code sections, function and delegates.
A function is a raw pointer (essentially) and a delegate is a pointer to 
function + "this" pointer.

> 2) Any hint to some reading about the supporting theory or
> rationale ?
>
> 3) When the onDraw function is actually called, whence does it
> takes its arguments from ? What is that Context ? Does it float
> around as some sort of implicit global object ? When was it
> instanciated ?

As I said above, for a delegate, it includes a context pointer.
So you can assume the arguments defined by the method, are required to 
call it.

Method decl:
bool onDraw(Context c, Widget w)

Callable:
bool delegate(Context, Widget) myEventFunc = ...
bool res = myEventFunc(myContext, myWidget);

> 4) Is &onDraw a predefined event belonging to the class
> DrawingArea ? Is the name of the onDraw function thus constrained
> ?
>
> 5) What is the chain of events leading to the "onDraw" event
> occuring ? I'd guess it's the 'showAll()' line, but by the way
> where does this 'showAll()' come from ? In the documentation [2],
> I don't see it as a method belonging to the class DrawingArea. Is
> it inherited from a superclass ?
>
>
>
> Thank you for the enlightment !
>
>
>
> ------------------------------------------------------------------------------------------------
>
> [1] http://britseyeview.com/software/articles/gsgtkd102.html
> [2] http://api.gtkd.org/src/gtk/DrawingArea.html



More information about the Digitalmars-d-learn mailing list