HP OpenVMS Systemsask the wizard |
The Question is: It is possible, as in C, to "assign" procedures and/or functions to a variable. Is such a way that the variable containing a reference to procedure/functions can be executed? The Answer is :
Yes, but not entirely within the standard language. Here is an example
program which shows how to do it using the IADDRESS function and %IMMED
operator. Note that it needs to be in two source files because Pascal
will only permit the "%immed" operator on external function and
procedure calls.
Also note that the procedures which are the target of the call must
be unbound. That means they cannot make references to variables defined
at higher scopes.
program RoutineByAddress(output);
(* The target routines *)
[UNBOUND] procedure a(i:integer);
begin WriteLn('routine a ',i); end;
[UNBOUND] procedure b(i:integer);
begin WriteLn('routine b ',i); end;
[UNBOUND] procedure c(i:integer);
begin WriteLn('routine c ',i); end;
(* the dispatch routine, in external module *)
procedure caller([UNBOUND] procedure p(i:integer); i:integer);EXTERNAL;
var proc : integer;
begin
(* first, calling via "caller" directly *)
caller(a,1);
(* now from a variable *)
proc:=iaddress(a);
caller(%immed proc,2);
proc:=iaddress(b);
caller(%immed proc,3);
proc:=iaddress(c);
caller(%immed proc,4);
end.
module Dispatch;
[GLOBAL] procedure caller(procedure p(i:integer); i:integer);
(* Dispatch routine for a procedure with a single integer argument *)
begin
p(i);
end;
end.
|