How to access private methods without helpers?

前端 未结 6 2077
孤独总比滥情好
孤独总比滥情好 2020-11-28 06:39

In Delphi 10 Seattle I could use the following code to work around overly strict visibility restrictions.

How do I get access to private variables?



        
6条回答
  •  臣服心动
    2020-11-28 07:28

    Assuming that extended RTTI is not available, then without resorting to what would be considered hacking, you cannot access private members from code in a different unit. Of course, if RTTI is available it can be used.

    It is my understanding that the ability to crack private members using helpers was an unintentional accident. The intention is that private members only be visible from code in the same unit, and strict private members only be visible from code in the same class. This change corrects the accident.

    Without the ability to have the compiler crack the class for you, you would need to resort to other ways to do so. For instance, you could re-declare enough of the TBase class to be able to trick the compiler into telling you where a member lived.

    type
      THackBase = class(TObject)
      private
        FMemberVar: integer;
      end;
    

    Now you can write

    var
      obj: TBase;
    ....
    MemberVar := THackBase(obj).FMemberVar;  
    

    But this is horrendously brittle and will break as soon as the layout of TBase is changed.

    That will work for data members, but for non-virtual methods, you'd probably need to use runtime disassembly techniques to find the location of the code. For virtual members this technique can be used to find the VMT offset.

    Further reading:

    • http://hallvards.blogspot.nl/2004/06/hack-5-access-to-private-fields.html
    • https://bitbucket.org/NickHodges/delphi-unit-tests/wiki/Accessing%20Private%20Members

提交回复
热议问题