Introducing Interfaces to an Existing Class Hierarchy in Delphi

Are there any side effects to changing the ancestor of the class hierarchy from TObject to TInterfacedObject so that I can implement interfaces further down the inheritance chain?

I have been programming in Delphi for several years, but have never seen interfaces. I am used to using them in other languages. Now that I am again involved in the Delphi project, I would like to start using them, but I know that they work a little differently than in Java or C #.

+4
source share
3 answers

If you already have existing code using the class, you will probably have to modify it to preserve interface references instead of object instances. Interfaces are counted and freed up automatically, as a result, any reference to the executing instance will become an invalid pointer.

+4
source

This will work fine as long as you inherit the class below at the top (bottom?) Of your hierarchy. This code ensures that your new classes are not freed up - as well as the default behavior of TInterfaceObject - you are apparently already freeing them yourself and want to keep it. This is actually what TComponent in VCL does - it supports interfaces, but is not counted by reference.

type TYourAncestor = class( TInterfacedObject ) function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end; implementation function TYourAncestor.QueryInterface(const IID: TGUID; out Obj): HResult; const E_NOINTERFACE = HResult($80004002); begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TYourAncestor._AddRef: Integer; begin Result := -1 // -1 indicates no reference counting is taking place end; function TYourAncestor._Release: Integer; begin Result := -1 // -1 indicates no reference counting is taking place end; 
+3
source

Apart from a few extra bytes in your instance size, no. This is probably the best way to do this.

+1
source

All Articles