Search code examples
delphiaccess-violationqueryinterface

Access violation exception from Delphi's Supports -> QueryInterface


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!!!


Solution

  • 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;