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

Peter Vreman peter at freepascal.org
Thu Nov 27 10:04:06 CET 2003


>> 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 :=  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?

The compiler should give an error. It is bad coding and only a
"undocumented feature" of delphi register calling that makes it working.
Because there is no full description of the register calling in delphi,
like how does it insert the self,parameter return or parent framepointer
parameters.








More information about the fpc-devel mailing list