pascal

How do you call a procedure given the procedure pointer in Pascal?


Given an array of pointers where those pointers are to procedures and where they pass a single pointer passed to a procedure, how do you call the passed pointer?

procedure CallPointerProc(Proc : Pointer);
begin
  // ???????????
end;

The old DOS method was fairly simple but inline is not available on Windows port so couldn't even convert to ebx,esp, etc..:

inline(
    $89/$E3/               {mov bx,sp}
    $36/$FF/$1F/           {call dword ptr ss:[bx]}
    $83/$C4/$04);          {add sp,4} 

Solution

  • In general, you should not pass a blank pointer but a type that describes the exact type of subroutine like parameters with their types and return type in case of a function.

    Example on how to declares procedure or function types

    type
      // A procedure with no parameters
      TProc = procedure;
    
      // A procedure that expexcts a string
      TStringProc = procedure(str: string);
    
      // A function that expects and returns a string
      TStringToStringFunc = function(str: string): string;
    

    A function that expects a pointer to a procedure and calls it:

    procedure CallPointerProc(Proc : TProc);
    begin
      Proc();
    end;
    

    A function that expects a blank pointer, casts it to a procedure and then calls that:

    procedure CallPointerProc(Proc : Pointer);
    var
      TypedProc: TProc;
    begin
      TypedProc := TProc(Proc);
      TypedProc();
    end;
    

    Demo code that works with both definitions of CallPointerProc above. Note that we use the @ symbol to get the address of a defined procedure or function.

    procedure Demo;
    begin
      Writeln('Hello World');
    end;
    
    begin
      CallPointerProc(@Demo);
      Readln;
    end.