Is it possible to typecast a callback function in Delphi?

471 views Asked by At

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)?

2

There are 2 answers

5
Keith Miller On BEST ANSWER

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;
2
blerontin On

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);