Fun with RTTI
Havent really had time to play with RTTI at all (it’s on my “check it out” list), but today i got inspired by the many cool examples out there and had to give it a go. First stop, dumping an object’s method names. Wish I had this 10 years ago when I made the basic bytecode compiler and 2D game engine GDX. It would have saved me weeks of COM hell.
function getMethodNames(Const aInstance:TObject):TStringList; var mContext: TRttiContext; mEntry: TRttiType; x: Integer; mText: String; mMethods: TArray<TRttiMethod>; const CNT_CLS_PREFIX: Array[Boolean] of string = ('','Class '); CNT_MTD_NAME: Array[Boolean] of string = ('function ','procedure '); begin result:=TStringList.Create; if aInstance<>NIl then begin mEntry := mContext.GetType(aInstance.ClassType); if mEntry<>NIL then Begin mMethods:=mEntry.GetMethods; for x:=low(mMethods) to high(mMethods) do begin mtext:=CNT_CLS_PREFIX[mMethods[x].IsClassMethod]; mText:=mtext + CNT_MTD_NAME[mMethods[x].ReturnType<>NIL]; mtext:=mText + mMethods[x].Name + '()'; if mMethods[x].ReturnType<>NIL then mText:=mText + ':' + mMethods[x].ReturnType.QualifiedName; mtext:=mText + ';'; result.Append(mText); end; end; end; end;
Also make sure you checkout some of the more interesting posts about RTTI out there, this article on Delphi sorcery caught my eye, and also this wiki post on Embarcadero’s servers. Attributes is definitively something I have sorely missed from C#. In a couple of weeks I’ll finally have time to read a book again – and will catch up.
This is going to simplify finishing off my tcp/ip remoting system radically. Mapping directly to loaded packages will give better performance than going via exported interfaces. Hm.. (wheels turning)