Download Free Pascal Language Reference Guide

Transcript
CHAPTER 7. INTERFACES
Type
IMyInterface = Interface
Function MyFunc : Integer;
end;
TMyClass = Class(TInterfacedObject,IMyInterface)
Function MyOtherFunction : Integer;
// The following fails in FPC.
Function IMyInterface.MyFunc = MyOtherFunction;
end;
This declaration tells the compiler that the MyFunc method of the IMyInterface interface
is implemented in the MyOtherFunction method of the TMyClass class.
7.4
Interfaces and COM
When using interfaces on Windows which should be available to the COM subsystem, the
calling convention should be stdcall - this is not the default Free Pascal calling convention, so it should be specified explicitly.
COM does not know properties. It only knows methods. So when specifying property
definitions as part of an interface definition, be aware that the properties will only be known
in the Free Pascal compiled program: other Windows programs will not be aware of the
property definitions.
7.5
CORBA and other Interfaces
COM is not the only architecture where interfaces are used. CORBA knows interfaces, UNO
(the OpenOffice API) uses interfaces, and Java as well. These languages do not know the
IUnknown interface used as the basis of all interfaces in COM. It would therefore be a
bad idea if an interface automatically descended from IUnknown if no parent interface was
specified. Therefore, a directive {$INTERFACES} was introduced in Free Pascal: it specifies what the parent interface is of an interface, declared without parent. More information
about this directive can be found in the Programmer’s Guide.
Note that COM interfaces are by default reference counted, because they descend from
IUnknown.
Corba interfaces are identified by a simple string so they are assignment compatible with
strings and not with TGUID. The compiler does not do any automatic reference counting for
the CORBA interfaces, so the programmer is responsible for any reference bookkeeping.
7.6
Reference counting
All COM interfaces use reference counting. This means that whenever an interface is assigned to a variable, it’s reference count is updated. Whenever the variable goes out of
scope, the reference count is automatically decreased. When the reference count reaches
zero, usually the instance of the class that implements the interface, is freed.
Care must be taken with this mechanism. The compiler may or may not create temporary
variables when evaluating expressions, and assign the interface to a temporary variable,
86