是否可以在 Delphi 中强制转换回调函数?
Is it possible to typecast a callback function in Delphi?
Delphi TList.Sort()
方法需要类型为 function (Item1, Item2: Pointer): Integer;
的回调函数参数来比较列表项。
我想摆脱回调函数中的类型转换,并想定义一个这样的回调函数:
function MyTypeListSortCompare( Item1, Item2 : tMyType ) : integer;
begin
result := WideCompareStr(Item1.Name, Item2.Name);
end;
...
MyList.Sort(tListSortCompare(MyTypeListSortCompare));
...
但不幸的是,这会触发 "Invalid typecast" 编译器错误。
是否有可能在 Delphi(2006) 中正确地转换函数指针?
可以进行类型转换,但需要在函数名称前加上“@”前缀:
var
MyList : TList;
begin
...
MyList.Sort(TListSortCompare(@MyTypeListSortCompare));
...
end;
正如评论中指出的那样,当 type-checked 指针关闭时不需要类型转换,所以在那种情况下这也有效:
MyList.Sort(@MyTypeListSortCompare);
我通常会这样做:
function MyTypeListSortCompare( Item1, Item2 : Pointer ) : integer;
var
LHS: TMyType absolute Item1;
RHS: TMyType absolute Item2;
begin
result := WideCompareStr(LHS.Name, RHS.Name);
end;
Delphi TList.Sort()
方法需要类型为 function (Item1, Item2: Pointer): Integer;
的回调函数参数来比较列表项。
我想摆脱回调函数中的类型转换,并想定义一个这样的回调函数:
function MyTypeListSortCompare( Item1, Item2 : tMyType ) : integer;
begin
result := WideCompareStr(Item1.Name, Item2.Name);
end;
...
MyList.Sort(tListSortCompare(MyTypeListSortCompare));
...
但不幸的是,这会触发 "Invalid typecast" 编译器错误。
是否有可能在 Delphi(2006) 中正确地转换函数指针?
可以进行类型转换,但需要在函数名称前加上“@”前缀:
var
MyList : TList;
begin
...
MyList.Sort(TListSortCompare(@MyTypeListSortCompare));
...
end;
正如评论中指出的那样,当 type-checked 指针关闭时不需要类型转换,所以在那种情况下这也有效:
MyList.Sort(@MyTypeListSortCompare);
我通常会这样做:
function MyTypeListSortCompare( Item1, Item2 : Pointer ) : integer;
var
LHS: TMyType absolute Item1;
RHS: TMyType absolute Item2;
begin
result := WideCompareStr(LHS.Name, RHS.Name);
end;