All other answers are options for copying memory directly, but I think this is the wrong approach. . This is a low-level language, and you use a high-level language, it's easy to make mistakes, and it's risky if your records contain manageable data types.
If you are trying to get the first two bytes of a single record element, try using a variant record (in C, concatenation). This is part of a record that can be solved in several ways, and here you want to access it either as a word or a series of bytes.
Try something like this (unverified, just typed in SO editor):
type TTwoBytes : packed record ByteA, ByteB : Byte; end; TValueRecord : packed record: case Boolean of True: (Value: SmallInt); False: (ValueBytes : TTwoBytes); end; end; TMyRecord = packed record Value1, Value2, Value3 : TValueRecord; end;
Then for the code:
var MyRecord: TMyRecord; MyBytes: TTwoBytes; begin MyRecord := ...; // Fill it with data here // Access the words / smallints by something like: MyRecord.Value1.Value MyBytes := MyRecord.ValueBytes; // The key bit: type safe assignment // Do something with MyBytes.ByteA or MyBytes.ByteB end;
What does this give you better than directly copying memory?
- This is safe: if you have more complex entries containing strings, interfaces, etc., it will still work without breaking the number of links.
- Safe type: no direct memory copy: you and the compiler know what you have and use.
- This is canonical: this is probably the โDelphi wayโ to do this. (Although there are several ways to structure records - if you look in the history of answers, it was worse from the beginning. I also think that the syntax "
case ... of " is silly for this, but this is another discussion ... :))
Some notes:
source share