[fpc-devel]Nested function as argument for TList.Sort

Florian Klaempfl Florian.Klaempfl at gmx.de
Thu Nov 27 08:54:51 CET 2003


Pedro Lopez-Cabanillas wrote:

> Hi,
> 
> The attached program compiles and works fine under Kylix 3, and also compiles 
> under fpc 1.9, but bombs with this message:
> 
> An unhandled exception occurred at 0x0807F0B5 :
> EAccessViolation : Access violation
>   0x0807F0B5
> 
> It happens on TObjectList.Sort when the argument is a local nested function. 
> It works well when the argument is a global function.
> 
> Regards,
> Pedro
> 
> 
> 
> ------------------------------------------------------------------------
> 
> program test6;
> 
> {$IFDEF FPC}
>   {$MODE DELPHI}
> {$ENDIF}
> 
> uses
>   Contnrs;
> 
> type
>   TestClass = class
>   private
>     key: Integer;
>   public
>     constructor Create(keyValue: Integer);
>     function getKey: Integer;
>   end;
> 
>   constructor TestClass.Create(keyValue: Integer);
>   begin
>     key := keyValue;
>   end;
> 
>   function TestClass.getKey: Integer;
>   begin
>     Result := key;
>   end;
> 
> var
>   list: TObjectList;
> 
>   procedure Populate;
>   begin
>     list := TObjectList.Create;
>     list.add(TestClass.Create(10));
>     list.add(TestClass.Create(5));
>     list.add(TestClass.Create(25));
>     list.add(TestClass.Create(15));
>   end;
> 
>   procedure SortAndPrint;
>     function TestCompare(ptr1, ptr2: pointer): Integer;
>     var
>       int1, int2: Integer;
>     begin
>       int1 := TestClass(ptr1).getKey;
>       int2 := TestClass(ptr2).getKey;
>       if int1 = int2
>       then Result := 0
>       else if int1 < int2
>            then Result := -1
>            else Result := 1;
>     end;
>   var
>     i: Integer;
>   begin
>     list.Sort(@TestCompare);
>     for i := 0 to list.Count-1 do
>     begin
>       WriteLn('Item ', i, ', key = ', TestClass(list.Items[i]).getKey);
>     end;
>   end;
> 
> begin
>   Populate;
>   SortAndPrint;
> end.

This is bad coding imho and works in Delphi only "by accident" because 
Delphi uses register calling conventions. Or are I'am wrong and sort 
expects a local procedure?






More information about the fpc-devel mailing list