Board index » delphi » Can you execute a procedure name if the name was built at runtime as a string?

Can you execute a procedure name if the name was built at runtime as a string?

Somewhat of a beginner in Delphi, but I need to build a procedure name at
runtime and execute it.  (The procedure itself has obviously been coded and
named, the user can select a interactively built menu item and I don't want
to hardcode a large case statement to execute the correct module.  I am
coming from a Clipper environment and we could do what was called an inline
compile which would compile a string into machine code which could then be
called using a code block - hope that was helpful.)

ANY help would be appreciated.

Thanks in advance,
David Collins
dcoll...@radiantsystems.com

 

Re:Can you execute a procedure name if the name was built at runtime as a string?


David,

You create menu-items at run-time. In most of the times you want the created
menu-items execute more or less the same code. Why don't you create a couple
of this procedures, and attach them to you OnClick-event of the newly
created menu-item.

You must have a specific reason to create a certain item, so my guess, you
can predict in advance what it should execute.

Building something at runtime is not really an option, you are better of
doing it in the above described way.

Sincerely,

Fred Jansma.

Re:Can you execute a procedure name if the name was built at runtime as a string?


On 10 Sep 1998 21:55:33 GMT, "David Collins"

Quote
<dcoll...@radiantsystems.com> wrote:
>Somewhat of a beginner in Delphi, but I need to build a procedure name at
>runtime and execute it.  (The procedure itself has obviously been coded and
>named, the user can select a interactively built menu item and I don't want
>to hardcode a large case statement to execute the correct module.  I am
>coming from a Clipper environment and we could do what was called an inline
>compile which would compile a string into machine code which could then be
>called using a code block - hope that was helpful.)

>ANY help would be appreciated.

>Thanks in advance,
>David Collins
>dcoll...@radiantsystems.com

David,

The same effect can be achieved, but there is no runtime compilation
in Delphi so the approach has to be a little different.

In Delphi procedures and functions can be passed as parameters (and
stored as variables - that is how Delphi handles events).  Here's a
simple example (untested) that should get you started.

procedure DoNumberOne(x : integer);
begin
  { code omitted }
end;

procedure DoNumberTwo(x : integer);
begin
  { code omitted }
end;

procedure DoNumberThree(x : integer);
begin
  { code omitted }
end;

type
  DoProc : procedure(x : integer);

var
  TheProcs : array[1..3] of DoProc;

procedure SetUp
begin
  TheProcs[1] := DoNumberOne;
  TheProcs[2] := DoNumberTwo;
  TheProcs[3] := DoNumberThree;
end;

procedure TestIt(which, x : integer);
begin
  if which in [1..3] then TheProcs[which](x);
end;

Other Threads