[fpc-pascal]Calling Procedures via pointers

Anton Tichawa anton.tichawa at chello.at
Wed Oct 29 22:50:23 CET 2003


Hello, Andy!

> Hi,
>
> I've been away from Pascal for about 10 years now and have just started to
> get back into it. So, spank me hard and call me a newbie if you must...
>
> Anyhow, onto the problem...
>
> I'm designing a unit (and a little test application) that i want to add a
> call back function to (as exit code)... i.e.
>
> The program gives the unit a pointer to the procedure MyCallback
>
> When an error occurs when the unit is communicating to the device (for
> example a serial device) if the pointer pCallback is not NIL I'd like to be
> able to call the user defined procedure, in this case MyCallBack.
>
> The idea is that I can compile the unit, then define the exit code in my
> individual applications... can someone give me some pointers (pun intended)
> on how to go about it....

Pascal supports procedure types, which are more reliable compared to untyped 
pointers. Procedure types also distinguish the types of the procedure's 
parameters (which is not important for your parameterless callback 
procedure). My suggestion is:


in program:

Procedure MyCallback();
Begin
        {do some stuff then}
        Halt;
End;

begin
  SetCallBack(MyCallBack);
end.


in unit:

type
  TCallBack = procedure;

var
  pCallBack: TCallBack;

Procedure SetCallBack(pProc : TCallBack);
Begin
       pCallBack := pProc;
End;

{ Carry out the procedure the user defined}

Procedure DoCallBack;

Begin
       If (pCallBack<>NIL) then
             pCallBack;
       else
             Halt;
End;

begin
    pCallBack := nil;
end.


hth,

Anton.

----------

Ing. Anton Tichawa
Volkertstrasse 19 / 20
A-1020 Wien
phone: +43 1 218 97 59
email: anton.tichawa at chello.at

----------

"Adas Methode war, wie sich zeigen wird, Tagträume in offenbar korrekte 
Berechnungen einzuweben."

Doris Langley Moore: Ada, Countess of Lovelace (London 1977).

----------




More information about the fpc-pascal mailing list