[fpc-pascal] Interface performance

Tony Whyman tony.whyman at mccallumwhyman.com
Fri Nov 11 10:56:45 CET 2016

On 11/11/16 09:46, Ryan Joseph wrote:
> Just as I got this message I’m running into some inexplicable memory related crashes casting from interfaces to objects and calling methods.  Are you sure you can just cast these around like that? The compiler seems to get confused and lose track of what the type actually is. In my first test this didn’t happen and I was able to use an interface as a type then cast it to an object, pass to a function and call a method. In the 2nd example the variable went from a couple classes first and died at the end. Seems very unstable.
You will probably need to post some examples to get more help. But here 
are some simple rules:

1. Classes that provide interfaces in most cases will have 
TInterfacedObject as their ancestor.

2. If you have an object with a class definition that explicitly 
supports a given interface then to get an interface reference all you 
need to do is to assign it to a variable of the interface type.

3. To get an object back from an interface you must use the "as" operator.


  IMyInterface = interface
     procedure MyProc;

  TMyObjectClass = class(TInterfacedObject,IMyInterface)
    procedure MyProc;

var MyObject1, MyObject2: TMyObjectClass;
       MyInterface: IMyInterface;

   MyObject1 := TMyObjectClass.Create;
   MyInterface := MyObject1;


   MyObject2 := MyInterface as TMyObjectClass;

   MyObject1.Free {OK for CORBA - will cause an exception in COM}
   {MyObject1, MyObject2 and MyInterface are now all invalid}

More information about the fpc-pascal mailing list