Name

IUnknown Interface

Syntax

type IUnknown = interface
  ['{00000000-0000-0000-C000-000000000046}']
  function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
  function _AddRef: Integer; stdcall;
  function _Release: Integer; stdcall;
end;

Description

The IUnknown interface is the base for all interfaces in Delphi. Every class that implements any interface must implement IUnknown also. For your convenience, Delphi declares the TInterfacedObject class, which implements IUnknown.

Delphi calls _AddRef when an interface is assigned to a variable or passed as an argument to a subroutine. It calls _Release automatically when an interface-type variable goes out of scope.

Tips and Tricks

  • IUnknown is the base interface in COM, which means any Delphi class can implement any COM interface. A Delphi program can use COM objects the same way it uses any other interface. COM is entirely optional, though. Many uses of interfaces are completely unrelated to COM.

  • Although the convention is that _AddRef and _Release manage a reference count, you are free to implement these methods any way you wish. If you want to take advantage of interfaces without using reference counting, you can implement these methods as stubs. Return a non-zero value because a zero result means the object’s reference count has reached zero.

  • Delphi implements the as operator for interfaces by calling QueryInterface. The most logical implementation of QueryInterface calls GetInterface, but you are free to implement it any ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.