Jump to content
Andrea Raimondi

Private class members raise an exception in 10.4.2 when I try to use RTTI on them

Recommended Posts

Hello!

 

Simple class:

 

{$RTTI EXPLICIT METHODS( [vcPrivate,vcProtected, vcPublic,vcPublished] )
                  PROPERTIES( [vcPrivate,vcProtected, vcPublic,vcPublished] )
                  FIELDS ( [vcPrivate,vcProtected, vcPublic,vcPublished] )}
  TTestClass = class
  private
    FTestProperty: Integer;
    procedure DoSomething;
    function Test: Boolean;
    procedure SetTestProperty(const Value: Integer);
  public
    procedure DoSomethingPublic;
    property TestProperty : Integer read FTestProperty write SetTestProperty;
  end;

Trying to access private members via this code:

RTTIUtils.GetFields( AnObj, Fields );

Which is defined like so::

procedure TClassRTTIUtils.GetFields(AnObject: TObject;
  var Fields: TArray<TRttiField>);
begin
  Fields := Ctx.GetType( AnObject ).GetFields;
end;

Ctx is a TRTTIContext (naturally, but worth mentioning).

 

10.4.2 raises an exception and I am not really sure why. 

 

I must be missing something obvious but can't see what.

 

Are there odd project options I have to set? I have browsed through them but can't find anything that will make me go "here it is!". 

 

Thanks!

Share this post


Link to post

It does not fail on private fields, but on retrieving type. You are passing object and GetType expects class

 

GetType(AnObject.ClassType)

 

Share this post


Link to post

There is another overload that takes Pointer... and it seems like this one is supposed to work with object instances, but it crashes instead.

Share this post


Link to post
15 hours ago, Dalija Prasnikar said:

There is another overload that takes Pointer... and it seems like this one is supposed to work with object instances, but it crashes instead.

Not really... it accepts PTypeInfo not object instance

Share this post


Link to post
On 3/24/2021 at 12:18 AM, Dalija Prasnikar said:

There is another overload that takes Pointer... and it seems like this one is supposed to work with object instances

Nope.  There is no method of TRttiContext that takes an object instance as input.  FindType() takes in a class type as a string, and GetType() takes in a class type as a TClass or PTypeInfo.

  • Like 2

Share this post


Link to post
9 minutes ago, Remy Lebeau said:

Nope.  There is no method of TRttiContext that takes an object instance as input.  FindType() takes in a class type as a string, and GetType() takes in a class type as a TClass or PTypeInfo.

Yep, I figured that out... I was still low on coffee when I took a peek at that code.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×