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

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 25 02:51:39 PDT 2014


On 05/25/2014 02:37 AM, Derix wrote:

 >         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 ?

Function pointer. What you are showing is a "callback function" usage.

 > 2) Any hint to some reading about the supporting theory or
 > rationale ?

I have some documentation here:

   http://ddili.org/ders/d.en/lambda.html

 > 3) When the onDraw function is actually called, whence does it
 > takes its arguments from ?

da.addOnDraw() simply stores the function pointer (onDraw in this case) 
for later use.

Later, it satisfies the call parameters by passing necessary Context and 
Widget objects that are known at that later time.

 > What is that Context ? Does it float
 > around as some sort of implicit global object ? When was it
 > instanciated ?

The library manages those objects.

Ali



More information about the Digitalmars-d-learn mailing list