The Delphi TList.Sort()
method expects a callback function argument of type function (Item1, Item2: Pointer): Integer;
for comparing the list items.
I'd like to get rid of typecasting within the callback function and would like to define a callback function like this:
function MyTypeListSortCompare( Item1, Item2 : tMyType ) : integer;
begin
result := WideCompareStr(Item1.Name, Item2.Name);
end;
...
MyList.Sort(tListSortCompare(MyTypeListSortCompare));
...
but unfortunately this triggers an "Invalid typecast" compiler error.
Is there some possibility to properly typecast function pointers in Delphi(2006)?
I normally do something like this:
function MyTypeListSortCompare( Item1, Item2 : Pointer ) : integer;
var
LHS: TMyType absolute Item1;
RHS: TMyType absolute Item2;
begin
result := WideCompareStr(LHS.Name, RHS.Name);
end;
A typecast is possible but requires to prefix the function name with "@":
var
MyList : TList;
begin
...
MyList.Sort(TListSortCompare(@MyTypeListSortCompare));
...
end;
As pointed out in the comments the typecast isn't needed when type-checked pointers are turned off, so in that case this also works:
MyList.Sort(@MyTypeListSortCompare);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.