Recent

Author Topic: [SOLVED]Query all enum value names through RTTI  (Read 2000 times)

soerensen3

  • Full Member
  • ***
  • Posts: 213
[SOLVED]Query all enum value names through RTTI
« on: May 25, 2018, 01:09:29 am »
Hi,

I try to get all possible values for an enum for my custom object inspector (In OpenGL so I can't use the LCL one).
So from that
Code: Pascal  [Select][+][-]
  1. TTestEnum = ( value1, value2, value3 );
  2.  
I want a stringlist with the lines 'value1', 'value2', 'value3'.
This code works for the enum above:
Code: Pascal  [Select][+][-]
  1.   if ( FPropInfo^.PropType^.Kind in [ tkEnumeration, tkBool ]) then
  2.     begin
  3.       Result:= TStringList.Create;
  4.       for i:= 0 to GetEnumNameCount( FPropInfo^.PropType ) - 1 do
  5.         Result.Add( GetEnumName( FPropInfo^.PropType, i ));
  6.       WriteLn( Result.Text );
  7.     end
  8.   else
  9.     Result:= nil;
  10.  

But for this enum it does not work.
Code: Pascal  [Select][+][-]
  1. TTestEnum2 = ( value1, value5 = 5, value7 = 7 ); // does only return value1
  2.  

Does anyone know a solution or should I not use this kind of enum?
« Last Edit: May 25, 2018, 02:44:13 am by soerensen3 »
Lazarus 1.9 with FPC 3.0.4
Target: Manjaro Linux 64 Bit (4.9.68-1-MANJARO)

soerensen3

  • Full Member
  • ***
  • Posts: 213
Re: Query all enum value names through RTTI
« Reply #1 on: May 25, 2018, 01:48:13 am »
Found the solution, in case anyone needs this as well:

Code: Pascal  [Select][+][-]
  1. function EnumGetNames( FPropInfo: PPropInfo ): TStringList;
  2. var
  3.   PS : PShortString;
  4.   i, Count: Integer;
  5.   s: String;
  6. begin
  7.   case ( FPropInfo^.PropType^.Kind ) of
  8.     tkEnumeration:
  9.       with GetTypeData( FPropInfo^.PropType )^ do begin
  10.         PS:= @NameList;
  11.         Count:= 0;
  12.  
  13.         Result:= TStringList.Create;
  14.         While ( PByte( PS )^ <> 0 ) do begin
  15.           Result.Add( PS^ );
  16.           PS:= PShortString( Pointer( PS ) + PByte( PS )^ + 1 );
  17.           Inc( Count );
  18.         end;
  19.  
  20.         Result.Delete( Result.Count - 1 ); // Last line is the unit name
  21.       end;
  22.     tkBool: begin
  23.       Result:= TStringList.Create;
  24.       Result.Text:= 'False' + LineEnding + 'True';
  25.     end
  26.   else
  27.     Result:= nil;
  28.   end;
  29. end;      
  30.  
Lazarus 1.9 with FPC 3.0.4
Target: Manjaro Linux 64 Bit (4.9.68-1-MANJARO)

 

TinyPortal © 2005-2018