The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 4,262 other subscribers

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.

  1. 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;
    • Touch the [WayBack] ClassName class function for each class, for instance in an initialization section or registration method, like this:
      TMyClass.ClassName;
      TMyOtherClass.ClassName;
  2. A small two step process
    1. Create a method like this: procedure EnsureRttiIsAvailable(const Classes: array of TClass); begin end;
    2. Pass the classes to it like this:
      EnsureRttiIsAvailable([TMyClass, TMyOtherClass]);

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.