PDA

View Full Version : Passing a procedure to another unit / form



Gadget
26-03-2005, 08:12 PM
I have looked into this before and I can't quite work out how to assign the procedure.

Examples show something like this:-

type TDebugProc = procedure(Text: string);

This is in effect a forward declaration on Form2 for a procedure that Form1 will pass it.

So I declare a variable on Form2:-

var
MyDebugProc: TDebugProc;

And I can call it like this:-

MyDebugProc('TEST MESSAGE');



The question is how to I populate this variable on Form2, from Form1 when the procedure declaration on Form1 is:-

TForm1.WriteDebug(Text: String);
begin
{DO SOME STUFF}
end;

??

On Form1 I want to do something like this:-

Form2.MyDebugProc := @WriteDebug;

M109uk
26-03-2005, 08:49 PM
Hi Gadget,

Im not completly sure what you mean but if im guessing write then this may help..

Form 2:

type
DebugProc = procedure (Text: String);

var
Form2: TForm2;
MyDebugProc: TDebugProc;


Form 1:

procedure WriteDebug(Text: String);
begin
//
end;


And you just assign 'MyDebugProc' with 'WriteDebug':

Unit2.MyDebugProc := WriteDebug;


Before you call MyDebugProc i recommend you check to see if it assigned with:

If Assigned(MyDebugProc) Then MyDebugProc(Text);


I cant remember how it works, but if the above gives an error try changing:

type
DebugProc = procedure (Text: String);


To:

type
DebugProc = procedure (Text: String) Of Object;

Clootie
26-03-2005, 08:59 PM
unit Unit1;
interface
type
TDebugProc = procedure(Text: string) of object;

TForm1 = class...
procedure RealDebugProc(Text: string);
end;
implementation
uses Unit2;
begin
Form2.DebugProc:= @Form1.RealDebugProc;
end.

///////////////////////////////////////
unit Unit2;
interface
uses Unit1;
type
TForm2 = class...
DebugProc: TDebugProc;
procedure DoSomething;
end;
implementation

procedure TForm2.DoSomething;
begin
if Assigned(@DebugProc) then
DebugProc('Output debug string');
end;

siim
27-03-2005, 04:16 PM
When I looked at the expression Assigned(@DebugProc) then I was pretty sure that this would always evaluate to true, because I thought that @DebugProc would return the address of the variable pointing to the procedure. But thats not the case here, Delphi help states this: "If F is a routine (a function or procedure), @F returns F?¢_Ts entry point."

Always nice to learn new things. :)

Anonymous
29-03-2005, 12:45 PM
Thanks =D

That worked a treat (once I moved a few things around).