Short Delphi tip: ensuring RTTI for classes is included
Posted by jpluimers on 2021/03/04
When using RTTI in Delphi, you really want the RTTI to be available.
The compiler includes RTTI for classes, as soon as it found that a class is touched by code that will be executed.
So in order to include RTTI for classes into the executable, you have to ensure you touch the class.
Basically there are two tricks for that.
- A small one step process which incurs a tiny bit of string overhead:
class function TObject.ClassName: string; begin Result := UTF8ToString(_PShortStr(PPointer(PByte(Self) + vmtClassName)^)^); end;
- A small two step process
- Create a method like this:
procedure EnsureRttiIsAvailable(const Classes: array of TClass); begin end;
- Pass the classes to it like this:
EnsureRttiIsAvailable([TMyClass, TMyOtherClass]);
- Create a method like this:
I like the second solution more, as it clearly states the intent.
The first trick is calling a function without using the result. This is a Pascal construct that looks odd, but is perfectly valid to use: basically you discard the result.
–jeroen
Leave a comment