2005. december 22., csütörtök

Create an interfaced object with no automatic destruction

Problem/Question/Abstract:

If I want automatic garbage collection with interfaces, I use TInterfacedObject as base class. What should I use, if I don't want automatic destruction? Is there a similar common base class or do I have to implement the IInterface methods myself?

Answer:

{BaseNonRefcountIntfObjU:
This unit provides a base class with a non-reference counted
implementation of IUnknown.

Author: Dr. Peter Below
Version 1.0, created 28 M�rz 2002
Last modified: 28 M�rz 2002}

unit BaseNonRefcountIntfObjU;

interface

type
{Derive classes that need a non-reference counted IUNknown
implementation from this class.}
TNonRefcountInterfacedObject = class(TObject, IUnknown)
protected
{IUnknown}
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;

implementation

uses
Windows;

function TNonRefcountInterfacedObject.QueryInterface(const IID: TGUID; out Obj):
HResult;
begin
if GetInterface(IID, Obj) then
Result := S_OK
else
Result := E_NOINTERFACE;
end;

function TNonRefcountInterfacedObject._AddRef: Integer;
begin
Result := -1; {-1 indicates no reference counting is taking place}
end;

function TNonRefcountInterfacedObject._Release: Integer;
begin
Result := -1; {-1 indicates no reference counting is taking place}
end;

end.


Nincsenek megjegyzések:

Megjegyzés küldése