Mega Code Archive

 
Categories / Delphi / Examples
 

Methodpointer

Subject: Re: Pointer to a object method? Jeff Jensen wrote: > > Hi > > I need to return a pointer to a function inside an Object, how > can I do this? > > I tried using @TMyObject.MyFunction - the compiler didn't > complain over this. There's no reason it should complain; but then, how do you use an untyped pointer like that to call the method? I'd recommend using a variable of the type of the method. Here's a quick project that demonstrates how this can be done: -------------------->8 cut here 8<-------------------- unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TStrMethodType = procedure( S: string ) of object ; TForm1 = class(TForm) BitBtn1: TBitBtn; BitBtn2: TBitBtn; BitBtn3: TBitBtn; procedure BitBtn1Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BitBtn3Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure TestMethod( S: string ) ; end; var Form1: TForm1; MethodPointer: TNotifyEvent; MethodPointer2: TStrMethodType ; implementation {$R *.DFM} procedure TForm1.TestMethod( S: string ) ; begin ShowMessage( S ) ; end ; procedure TForm1.FormCreate(Sender: TObject); begin MethodPointer := BitBtn1Click ; MethodPointer2 := TestMethod ; end; procedure TForm1.BitBtn1Click(Sender: TObject); begin ShowMessage( 'BitBtn1Click' ) ; end; procedure TForm1.BitBtn2Click(Sender: TObject); begin MethodPointer( Sender ) ; end; procedure TForm1.BitBtn3Click(Sender: TObject); begin TestMethod( 'Calling TestMethod directly' ) ; MethodPointer2( 'Calling TestMethod via Method Pointer' ) ; end; end. -------------------->8 cut here 8<-------------------- HTH Stephen Posey slposey@concentric.net