我已阅读这些问题和答案
How to change the implementation (detour) of an externally declared function
但我无法弄清楚如何修补位于另一个单元中的类的私有(private)方法。
检查此示例,我想修补 Bar
过程。
Unit ThidParty;
Interface
Type
TFoo =Class
private
procedure Bar;
end;
我认为关键是找到一种方法来获取私有(private)方法的地址。
那么,我如何修补 Delphi 类的私有(private)方法?
最佳答案
下面概述的解决方案适用于 Delphi Seattle 及以上版本。 您可以使用 class helper破解该类:
单元1
type
TTest = class
private
procedure Foo;
end;
单元2
type
TMyTestHelper = class helper for TTest
function GetFooAddress: Pointer;
end;
function TMyTestHelper.GetFooAddress: Pointer;
var
MethodPtr: procedure of object;
begin
MethodPtr := Self.Foo;
Result := TMethod(MethodPtr).Code;
end;
function FooAddress: Pointer;
begin
Result := TTest(nil).GetFooAddress;//don't need to instantiate an object
end;
将 FooAddress
的返回值传递给您的修补函数之一,这样您就万事大吉了。
但是,从 Delphi 10.1 Berlin 开始,这不再有效!类助手不能再访问严格 protected 、严格私有(private)或私有(private)成员。这个“功能”实际上是一个编译器错误,Embarcadero 现已在柏林修复。你运气不好。
关于delphi - 如何修补 Delphi 类的私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10156430/