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.

e.g.

type
 IMyInterface = interface
    procedure MyProc;
 end;

 TMyObjectClass = class(TInterfacedObject,IMyInterface)
 public
   procedure MyProc;
 end;

var MyObject1, MyObject2: TMyObjectClass;
      MyInterface: IMyInterface;

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

  MyInterface.MyProc;

  MyObject2 := MyInterface as TMyObjectClass;

  MyObject1.Free {OK for CORBA - will cause an exception in COM}
  {MyObject1, MyObject2 and MyInterface are now all invalid}
end;
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to