How I can patch a private method of a delphi class?

后端 未结 1 674
遇见更好的自我
遇见更好的自我 2020-12-09 10:46

I have read these questions and answers

How to change the implementation (detour) of an externally declared function

Patch routine call in delphi

but

相关标签:
1条回答
  • 2020-12-09 11:37

    The solution outlined below works for versions up to and including Delphi Seattle. You can use a class helper to crack the class:

    Unit1

    type
      TTest = class
      private
        procedure Foo;
      end;
    

    Unit2

    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;
    

    Pass the return value from FooAddress to one of your patching functions and you are golden.

    However, starting with Delphi 10.1 Berlin, this no longer works! Class helpers can no longer access strict protected, strict private or private members. This "feature" was actually a compiler bug that Embarcadero has now fixed in Berlin. You are out of luck.

    0 讨论(0)
提交回复
热议问题