Undocumented Delphi record alignment directive

In Delphi XE5, the align directive was introduced, and is undocumented.

The new directive, align, is placed at the end of a record declaration, with a required parameter of an expression that evaluates to 1, 2, 4, 8 or 16.

Below are examples of the align directive:

  ConstExpr = 16;
  PX = ^TX;
  TX  = record
     {record declarations}
  end align ConstExpr;

  PX2 = ^TX2;
  TX2  = record
     {record declarations}
  end align 4;

  PX3 = ^TX3;
  TX3  = record
     {record declarations}
  end align (1 shl 2);

  X: PX;

ConstExpr can be a number, or it can be a constant, or an expression, eg, (x+y) or (1 shl 2), etc, that is a multiple of 2, so that it evaluates to a maximum of 16.

Also, if a pointer to the above record is declared, and used in a memory allocation, such as New(X), the compiler will translate the New(X) request to GetMem(X, PaddedSizeOfX) where PaddedSizeOfX is a multiple of the ConstExpr that is greater than the size of the actual record, provided the record is not a packed record.

So for example, if the total size of TX is only 9 bytes, but ConstExpr is set as 16, New(X) is then translated as GetMem(X, 16). If TX is 30 bytes, then New(X) is translated as GetMem(X, 32).

If you provided an expression that is not a multiple of 2, then you'll get the following error:

E2573 Illegal value for the ALIGN directive (valid for one of 1, 2, 4, 8 or 16)

The error is the same error you get when you pass the wrong parameter to the $ALIGN compiler directive, so it seems that the record alignment directive is a shorthand to the $ALIGN directive.


Published Tue, 27 May 2014 @ 2:28 PM by chuacw
Related articles: , ,

Leave a Comment

Enter the following code to ensure that your comment reaches the intended party:
Enter the numbers you see in the image: