Skip to content

RTTI does not work like delphi

System Information

  • Operating system: Windows
  • Processor architecture: x86-64
  • Device: Computer
  • FPC version: 3.3.1 [2024/05/19] for i386, Trunk 10d74029

Example Project

program test;

{$ifdef FPC}
{$mode delphi}
{$M+}
{$modeswitch advancedrecords}
{$else}
{$APPTYPE CONSOLE}
{$endif}

uses
  {$IFDEF DCC}System.{$ENDIF}SysUtils, {$IFDEF DCC}System.{$ENDIF}TypInfo, {$IFDEF DCC}System.{$ENDIF}Rtti;

type
  {$RTTI EXPLICIT
     PROPERTIES([vcPrivate,vcProtected,vcPublic,vcPublished])
     FIELDS([vcPrivate,vcProtected,vcPublic,vcPublished])
     METHODS([vcPrivate,vcProtected,vcPublic,vcPublished])}

  TPerson = record 
  private
    FName: string;
    FAge: Integer;
  public
    procedure DisplayInfo;
  end;

procedure TPerson.DisplayInfo;
begin
  WriteLn('Name: ', FName);
  WriteLn('Age: ', FAge);
end;

var
  Context: TRttiContext;
  RttiType: TRttiType;
  valfields: TArray<TRttiField>;
  Person: TPerson;
  i: Integer;
begin
  Person.FName := 'Alice';
  Person.FAge := 25;
  Person.DisplayInfo;

  Context := TRttiContext.Create;
  try
    RttiType := Context.GetType(TypeInfo(TPerson));
    if Assigned(RttiType) then
    begin
      valfields := RttiType.GetFields;
      WriteLn('Fields of TPerson: ', Length(valfields));
      for i := Low(valfields) to High(valfields) do
      begin
        WriteLn('Field: ', valfields[i].Name, ' - Type: ', valfields[i].FieldType.Name);
      end;
    end
    else
      WriteLn('No RTTI information available for TPerson.');
  finally
    Context.Free;
  end;
end.

The above programs are compiled with fpc and run as follows.

# fpc test.pp
Free Pascal Compiler version 3.3.1 [2024/05/19] for i386
Copyright (c) 1993-2024 by Florian Klaempfl and others
Target OS: Win32 for i386
Compiling test.pp
Linking test.exe
63 lines compiled, 0.2 sec, 310448 bytes code, 10948 bytes data

# test
Name: Alice
Age: 25
Fields of TPerson: 0

Relevant 3rd party information

The above program is compiled by delphi and the results are as follows

# dcc32 test.pp
Embarcadero Delphi for Win32 compiler version 36.0
Copyright (c) 1983,2024 Embarcadero Technologies, Inc.
test.pp(64)
65 lines, 0.09 seconds, 874208 bytes code, 43132 bytes data.

# test
Name: Alice
Age: 25
Fields of TPerson: 2
Field: FName - Type: string
Field: FAge - Type: Integer
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information