[Lazarus] Example requested for TList and Sort using data type of Object (or record).

Sven Barth pascaldragon at googlemail.com
Wed May 11 17:30:55 CEST 2011


Am 11.05.2011 15:28, schrieb Marcos Douglas:
> On Wed, May 11, 2011 at 9:35 AM, Sven Barth<pascaldragon at googlemail.com>  wrote:
>> Am 11.05.2011 14:30, schrieb Marcos Douglas:
>>>
>>> On Wed, May 11, 2011 at 3:51 AM, Mattias Gaertner
>>> <nc-gaertnma at netcologne.de>    wrote:
>>>>
>>>> function SortComponentsForName(Item1, Item2: Pointer): integer;
>>>> var
>>>>   Comp1: TComponent absolute Item1;
>>>>   Comp2: TComponent absolute Item2;
>>>> begin
>>>>   Result:=CompareText(Comp1.Name,Comp2.Name);
>>>> end;
>>>
>>> I did not know about 'absolute' yet... what is the vantage?
>>> Can you give me a link about it, please?
>>
>> See here (in the list point 6):
>> http://freepascal.org/docs-html/ref/refse20.html#x52-590004.2
>>
>> It allows you to declare a variable that has the same location as another
>> variable or parameter (but it does not need to have the same type). In the
>> example written by Matthias Comp1 contains the value of Item1 from the
>> "begin" on. The other way to achive this is the following:
>>
>> function SortComponentsForName(Item1, Item2: Pointer): Integer;
>> var
>>   Comp1, Comp2: TComponent;
>> begin
>>   Comp1 := TComponent(Item1);
>>   Comp2 := TComponent(Item2);
>>   Result := CompareText(Comp1.Name, Comp2.Name);
>> end;
>
> OK... and an Exception occur if the conversion fail?
> I always use the other way, ie, type-conversion... but thanks.

There won't be an exception as a result of the conversion (because there 
is none), but maybe nasty exceptions or side effects later on.

For example:

type
   TTest1 = record
     i: LongInt;
   end;

   TTest2 = record
     q: Int64;
   end;

procedure Foo;
var
   t1: TTest1;
   t2: TTest2 absolute t1;
begin
   ...
end;

As you see TTest2 is larger than TTest1, so depending on the 
circumstances of the run you might trigger an access violation or you 
might corrupt data on the stack.

If you use absolute with classes that don't inherit from another then 
you can get the same nasty results if you do a normal cast between them.

Basically you need to know what you do.

Note: The following works as well and can be used as a safety measure in 
case of classes:

procedure Bar(a: TObject);
var
   b: TComponent absolute a;
begin
   if a is TComponent then
     b.SomeMethodOfTComponent;
end;

Regards,
Sven






More information about the Lazarus mailing list