Mega Code Archive

 
Categories / Delphi / Examples
 

Record alignment in 32bit pascal

Question: When I try to call a function in a DLL and pass a record, the field members are not aligned in the same way the dll expects. The DLL was constructed with a C compiler using record member alignment. How can I achieve a like record alignment with Delphi? Answer: The following example demonstrates padding a record to 32 bit boundaries. Adjustments will need to be made to interface with the compiler directives that were in place when the dll was built, as there are differing rules that can be in force during compile time in regards to record alignment. Some compilers may have options to (for instance) guarantee that every field is not only 32 bit aligned, but each field will also be located on an even 32 bit boundary. It may even be possible that the given compiler guarantees that the entire record is aligned to an even number of 32 bit "chunks". type SomeAlignedRecord = {$IFDEF WIN32} packed {$ENDIF} record AByteField : byte; {add three bytes to align field to 32 bits} UnusedPaddingA : array[1..3] of byte; AWordField : word; {add two bytes to align field to 32 bits} UnusedPaddingB : array[1..2] of byte; ACharField : char; {add three bytes to align field to 32 bits} UnusedPaddingC : array[1..3] of byte; {align record to an even number of 32 bit chunks} FinalUnusedPadding : array[1..4] of byte; end;