Interface method as an event handler

Can I use the interface method as event handlers in Delphi 2007? Simple versions do not work:

type TMyEvent = procedure of object; IMyInterface = interface procedure Handler; end; TMyClass = class(TInterfacedObject, IMyInterface) public procedure Handler; end; var ev: TMyEvent; obj: TMyClass; intf: IMyInterface; begin obj := TMyClass.Create; intf := obj; ev := obj.Handler; // compiles ev := intf.Handler; // <== Error E2010 (incompatible types) end. 

Adding @ or Addr changes the error to E2036 (variable required).

Update: This

 procedure IntRefToMethPtr(const IntRef; var MethPtr; MethNo: Integer); type TVtable = array[0..999] of Pointer; PVtable = ^TVtable; PPVtable = ^PVtable; begin //QI=0, AddRef=1, Release=2, etc TMethod(MethPtr).Code := PPVtable(IntRef)^^[MethNo]; TMethod(MethPtr).Data := Pointer(IntRef); end; var ev: TMyEvent; intf: IMyInterface; begin intf := TMyClass.Create; IntRefToMethPtr(intf, ev, 3); ev; end. 

works. However, I do not really like magic 3.

+4
source share
1 answer

A cleaner solution is to implement IInterfaceComponentReference or something similar for your base class and use this to get the ref class.

The above code will not work, for example. FPC and other compatible devices. Their VMT structure is slightly different. And even on Delphi, further expansion of the language can cause this.

The ideal solution is to have a completely separate “interface method” for the method, but I wonder if this is worth worrying about.

+2
source

All Articles