[fpc-pascal] Re: Delphi's anonymous functions in Free Pascal

Bernd prof7bit at googlemail.com
Sat Nov 5 23:25:23 CET 2011


2011/11/5 Michael Van Canneyt <michael at freepascal.org>:
> Procedure SomeOuter;
>
> Var
>  d,e,f : SomeType;
>
>  Procedure
> SomeInner(targetobject:ttargetobject;a:integer;b:someobject;c:string)
>   begin
>      targetobject.destinationprocedure(a,b,c);
>   end;
>
> begin
>  Targethread.queue(@SomeInner(aobject,d,e,f));
> end;
>
> No difference with 'closure', except more readable.
>
> Michael.

I doubt that this would even compile. Also As I pointed out already
the example was wrong, the procedure does not have any arguments, the
closure must be "closed over" these variables.

and this:

begin
  Targethread.queue(@SomeInner);
end;

would compile but it would just pass the procedure variable. This is
not a closure. How is the other thread supposed to know the values of
the variables that existed only in the scope of SomeOuter?

A closure would be something like this:

Procedure SomeOuter;
Var
  d,e,f : SomeType;

  Procedure SomeInner
  begin
    targetobject.destinationprocedure(a,b,c);
  end;

begin
  Targethread.queue(SomeInner);
end;

The compiler would need to create an object on the heap containing the
procedure *along* with the needed variables a,b,c and then pass the
entire object. The receiving side could then call this method and it
would still have access to these variables.

A closure has enclosed variables from the surrounding scope where it
was created, hence the name 'closure'. You cannot do this with a
procedure variable alone, you need an object on the heap to contain
the enclosed variables. The Delphi compiler will behind the scenes
create a reference counted object with an 'invoke' method (the
procedure SomeInner) and all its needed variables.

It is basically a syntactic shortcut to explicitly defining this
class, and creating an instance of it.



More information about the fpc-pascal mailing list