Sort old Contnrs.TObjectList on Win64

We have some old classes using Contnrs.TObjectList , and in some cases, custom comparison functions are used to sort these lists using something like this:

 procedure TMyClass.SortItems; function CompareFunction(Item1, Item2: Pointer): Integer; begin Result := TSomeItem(Item1).Value - TSomeItem(Item2).Value; end; begin Sort(@CompareFunction); end; 

This code worked without problems compiling for Win32, but when we compiled it for Win64, we found that sorting no longer worked.

I fixed some of them using Generics.Collections.TObjectList<T> instead, and changing the CompareFunction and how it is called. Therefore, I assume that it is related to how CompareFunction is CompareFunction by prefixing it with the @ operator, which, as I understand it, refers to the address of the function.

Why the above code does not work on Win64, and what is the way to fix it?

+5
source share
1 answer

TObjectList.Sort() expects a standalone function for its callback.

The inner function shares the stack stack of its parent function (therefore, it can access the parent local variables and parameters). Thus, you cannot use an internal function as a callback. You went with it to 32-bit, due to an accident in how the functions work on 32-bit. But this will no longer work on the 64-bit version.

You need to move CompareFunction() yourself, for example:

 function CompareFunction(Item1, Item2: Pointer): Integer; begin Result := TSomeItem(Item1).Value - TSomeItem(Item2).Value; end; procedure TMyClass.SortItems; begin Sort(@CompareFunction); end; 

This will work on both 32-bit and 64-bit.

+7
source

Source: https://habr.com/ru/post/1273603/


All Articles