The process type in Pascal is similar to the function pointer in C.For the sake of uniformity, the following is called a function pointer. The Declaration of the function pointer only requires the parameter list. If it is a function, a return value is added. The following describes the function pointers pointing to non-object (general) functions/procedures.
For example, declare a process type with an integer parameter passed by reference:
Type
Intproc = procedure (VAR num: integer );//Intproc is a function pointer to a process.
This process type is compatible with routines with identical parameters, that is, variables declared by it can point to any such function and call the function through it.
The following is a compatibility routine:
ProcedureDoublethevalue (VaRValue: integer );BeginValue: = value * 2;End;
Function pointers can be used for two different purposes: declaring a variable of the function pointer type; or passing a function pointer as a parameter to another routine. With the given type and Process Declaration above, you can write the followingCode:
VaR
IP: intproc;
X: integer;
Begin
IP: = doublethevalue;
X: = 5;
IP (X );
End;
Although this call method is more difficult than direct call, why should we use this method?
(1) In some cases, you can determine which function to call in actual conditions (runtime) and use the same expression according to the conditions, it is flexible to call different functions.
(2) using function pointers, we can implement delegation, which is fully realized in. net, but Delphi can also implement
(3) Implement callback
In Delphi, a function can be passed as a parameter through a function pointer and then called in another function.
1) First, declare the function pointer type tfunctionparameter.
Type
Tfunctionparameter = function (const value: integer): string;
2) define the function to be passed as a parameter
Function one (const value: integer): string;
Begin
Result: = inttostr (value );
End;
Function two (const value: integer): string;
Begin
Result: = inttostr (2 * value );
End;
3) define the function that will use the dynamic function pointer Parameter
Function dynamicfunction (F: tfunctionparameter; const value: integer): string;
Begin
Result: = f (value );
End;
4) Examples of using the above Dynamic Function
VaR
S: string;
Begin
S: = dynamicfunction (one, 2006 );
Showmessage (s); // will display "2006"
S: = dynamicfunction (two, 2006);
showmessage (s ); // will display "4012"
end;