[fpc-pascal] casting interfaces and objects

Marco van de Voort marcov at stack.nl
Sun May 18 23:07:12 CEST 2008

> I have two questions about interface usage.
> 1. How interfaces are to handle when casting?
> Theoretically it should be safe to do this:
> TObservable = class
> public
>   procedure Register( obsv: IObserver );
> private
>   procedure NotifyObservers(param: TParameter);
>   fObservers: TFPObjectList;
> end;
> procedure TObservable.Register( obsv: IObserver );
> begin
> 	fObservers.add(TObject(obsv));
> end;

No it is not safe. The interface points to an interface table, and you cast
it if it were a class VMT.

Have a look at IInterfaceComponentReference and use/implement the
getcomponent method. Note that this was added post-2.2.0

More information about the fpc-pascal mailing list