Garbage Collector
by: G.E. Ozz Nixon Jr.
Published: July 2009
©opyright 2009 by Friends of FPC
While working with Alexander on paxCompiler for Windows, Linux and Mac OS X, a common problem is implementing
a true garbage collector (This problem exists in a wide range of script engines, even popuplar ones like PHP.),
I came across an example using IUNKNOWN Interface. The trick is when an interface goes out of scope the Release()
method is automatically called, if it contains a pointer to the actual object it can call that object.free for
you automatically.
IUnknown Interface
Enables clients to get pointers to other interfaces on a given object through the QueryInterface method, and
manage the existence of the object through the AddRef and Release methods. All other COM interfaces are inherited,
directly or indirectly, from IUnknown. Therefore, the three methods in IUnknown are the first entries in the VTable
for every interface.
About IUnknown, it works on Windows 2000 and later, its IID_IUnknown is defined as
00000000-0000-0000-C000-000000000046,
and this code has been ported and test with FPC on Windows, Linux and Mac OS X.
Download garbagecollector.pp Source for Free Pascal Compiler
program test;
{$MODE DELPHI}{$H+}
uses garbagecollector;
type
TTest = class(TObject)
public
constructor Create;
destructor Destroy; override;
procedure Test;
end;
constructor TTest.Create;
begin
WriteLn('Create()');
end;
destructor TTest.Destroy;
begin
WriteLn('Destroy()');
inherited;
end;
procedure TTest.Test;
begin
WriteLn('Test()');
end;
procedure TestProc;
var
SafeGuard : ISafeGuard;
obj : TTest;
begin
obj := TTest(Guard(TTest.Create, SafeGuard)); // Create!
obj.Test;
end;
begin
TestProc;
end.
Now when compiled and executed, you will see your output state Create(), Test() and Destroy(), even
though you have obviously not called obj.Free; in your code. After the call to obj.Test your "obj"ect
goes out of scope and can be destroyed. Due to the design of most script engines they do not track
a reference counter to their variables, nor are they doing a stack tracker (another solution I developed
for my JavaScript Interpreter) and eventually a long script (one which runs non-stop for days will
eventually run out of RAM and potentially bring the host operating system down.
G.E. Ozz Nixon Jr.