[fpc-pascal]no refcounted interfaces

Dean Zobec dezobec at tin.it
Thu Apr 8 21:42:07 CEST 2004


I've talked with some friends of mine about the use of Interface base classes 
without reference counting in Delphi 
like this
type
  TNoRefCount = class(TObject, IUnknown)
  protected
    function QueryInterface(const IID:TGUID; out Obj):HResult; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
  end;
 
function TNoRefCount.QueryInterface(const IID:TGUID; out Obj): HResult;
begin
  if GetInterface(IID, Obj) then
    Result := 0
  else
    Result := Windows.E_NoInterface;
end;
 
function TNoRefCount._AddRef: Integer;
begin
  Result := -1
end;
 
function TNoRefCount._Release: Integer;
begin
  Result := -1
end;

 
We are all experiencing the same kind of problems:

1) there's no easy way to obtain a TObject from an interface (whereas there's 
no particular reason not to have it. A solution proposed was to implement an 
AsObject method in  all the interfaces used.
2) there's no FreeAndNil function that would free the interface and the object 
instance. 

It would be nice to be able to do something like this in an abstract factory:
var
  MyRef: ISomeInterface;
begin
  MyRef := SomeFactory.CreateObject as ISomeInterface;
  try
    ...use MyRef...
  finally
    MyRef.AsObject.Free;
    MyRef := nil;
  end;
end;

Any Idea of a solution in free pascal?

Ciao, Dean




More information about the fpc-pascal mailing list