functiondelphicastingdelphi-2006

Is it possible to typecast a callback function in Delphi?


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


Solution

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