How to translate the CC ++ program into Delphi (10)

zhaozj2021-02-17  47

3.6.3. Packed Records (Alignment)

IF a replaord is packed (aligned) THE Starting Byte of a field (AND conveuently also of the record) IS aligned with the first byte of a word (16-bit or 2-byte align) OR of A DWORD (32-bit OR 4-Byte Alignment). This Significantly Speeds CPU Access To The Fields, But Consumes More Memory.

The older APIs (from the 16-bit world) usually use packed structures (one or two byte alignment) It is the default in 16-bit Delphi:. There is no difference under Delphi 1 if you write record or packed record.

Four-byte alignment is the default under delphi32, although Some apis do use packed records under win32.

IT's Important to Know Which Type Of Alignment Is Used in an API, Because The Size of A Record Depends on the alignment.

The Following Example Explains The Difference Between The Coding of 2-byte and 4-byte Alignment:

TMYRECNOTPACKED = Record

Fielda: Word;

Fieldb: longint;

Fieldc: Byte;

END;

TMYRECPACKED = PACKED Record

Fielda: Word;

Fieldb: longint;

Fieldc: Byte;

END;

Offset 0 1 2 3 4 5 6 7 8 9 10 11 TMYRECUNPACKED A.. B B B C.... TMYRECPACKED A A B B B B C

Now, how to determine WHETHER PACKING IS Required or Not. In The Microsoft Apis, Two Methods Are Used. One Is Clear and Simple:

#pragma pack (n)

Use the packed keyword if n IS 1 or 2, but don't use packed if n is 4.

However, Microsoft Uses #include to control packing by putting the packing pragma in the include file. The follication incrude files area used to control the packing method:

#includs ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

IF a Header File Contains the Following Line

#include

You can interpret it as #pragma pack (1) and use the packed keywords in Records from count of pshpa ?h or to an incline of poppack.h.

Four-byte alignment (non-packed records) is the default under Delphi32. But what if the user changes the compiler options and switches off 4-byte alignment? If you need to ensure that 4-byte alignment is enabled you must insert the following Line at the top of the unit:

{$ Align on}

A Unit Header Must Look at Least Like this:

Unit myunit;

{$ Align on}

You can use the the {$ align} Directive Instead Of ExPlicitly Using The Packed Keyword, TOO, But I PreferRidit Packing Because It overrides {$ align on} and makes things quite specific.

NOTE: A field whose length is an odd number of bytes presents a problem if you encounter #pragma pack (2) and use the packed keyword for translating it The field will be close packed on a byte boundary when it should be packed on a. Word Boundary. a Solution Is Being Sough for Handling This Situation.

Back to Contents

转载请注明原文地址:https://www.9cbs.com/read-30420.html

New Post(0)