1

I have the following piece of code:

  for i := 0 to FControlList.Count - 1 do
      if Supports(IMyControl(FControlList[i]), IMyControlEx) then
      begin
        MyControlEx := IMyControl(FControlList[i]) as IMyControlEx;
        MyControlEx.DoYourMagic(Self, SomeData);
      end;

This code is called many times during my application execution, but in some specific cases it fails inside the Supports() method. And more specifically - it seems to fall inside the QueryInterface() call within the Supports() method.

I checked that FControlList is not nil and FControlList[i] is not nil and it still happens.

Any idea will be appreciated!!!

Lars Truijens
  • 42,837
  • 6
  • 126
  • 143
Sharon
  • 83
  • 1
  • 9
  • 1
    Can you remove the cast to IMyControl in the Supports call? What is FControlList, a IInterfaceList? – mjn Mar 21 '10 at 10:32
  • Also note that TControl can have their own life cycle management, even if they are subclasses of TInterfacedPersistent they do not use reference counting. See http://stackoverflow.com/questions/2182612 – mjn Mar 21 '10 at 11:29
  • It is just because TInterfacedPersistent doesn't use reference counting. Otherwise TInterfacedObject were used. – Uwe Raabe Mar 21 '10 at 12:03
  • Supports requires a GUID to be defined for the interface, I'm assuming you've done so for IMyControlEx. – Alan Clark Mar 21 '10 at 20:21

1 Answers1

5

Even if FControlList[I] is not nil, that doesn't mean it points to valid data. The underlying object instance may have been freed already.

I also suggest to remove the type cast to IMyControl. Supports can take objects and interfaces as parameter, even if they are nil, and produce the desired result.

In addition you may consider using this way of calling supports for your convinience and readabilty of the code:

if Supports(FControlList[i], IMyControlEx, MyControlEx) then
begin
  MyControlEx.DoYourMagic(Self, SomeData);
end;
Uwe Raabe
  • 45,288
  • 3
  • 82
  • 130
  • Looks like you're right and indeed it has some freed data. The problem is very complicated and I haven't solved it yet, but still - that's the answer. Thanks! – Sharon Mar 22 '10 at 06:53