[fpc-pascal] casting interfaces and objects
Marc Santhoff
M.Santhoff at t-online.de
Sun May 18 23:35:25 CEST 2008
Am Sonntag, den 18.05.2008, 23:07 +0200 schrieb Marco van de Voort:
> > 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.
I see. I indeed had a somewhat "hacky" feeling using that cast ...
Since the compiler dod not warn about using the "as" operator I assume
it is safe? Like this:
procedure TObservable.DeRegister( obsv: IObserver );
var
i: integer;
begin
if (fObservers.count<=0) then exit;
for i:=0 to fObservers.count-1 do begin
if ((fObservers[i] as IObserver)=obsv) then begin
fObservers.delete(i);
fObservers.pack;
exit;
end;
end;
end;
(Although this example will no longer exist when using an
T/IInterfaceList.)
> Have a look at IInterfaceComponentReference and use/implement the
> getcomponent method. Note that this was added post-2.2.0
I'll have a look and put it on my todo-list.
Thanks a lot,
Marc
More information about the fpc-pascal
mailing list