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 way you want. Be sure to return S_OK (zero) for success; any other result from QueryInterface tells Delphi’s as operator to raise runtime error 23 (EIntfCastError).

  • If you just want to test whether an interface is supported, and you don’t want the overhead of raising an exception, call QueryInterface directly instead of using the as operator, or call Supports in the SysUtils unit.

See Also

As Keyword, Interface Keyword
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset