View Full Version : Stream writing problem

21-06-2004, 01:18 PM
I have a question regarding 2 different methods of writing a structure to a stream. firstly, writing it as one variable and secondly writing the variables in the stream individually. I would expect both methods to produce the same data in the stream and in the same order - but that isn't the case.

TStructure = record
variable1 : byte;
variable2 : Single;

AStream : TMemoryStream;
AStruct : TStructure;

AStream := TMemoryStream.Create;
AStream.Seek(0, 0);

// method 1
AStream.Write(AStruct, SizeOf(TStructure));

// method 2
AStream.Write(AStruct.variable1, 1);
AStream.Write(AStruct.variable2, SizeOf(Single));

So, any idea why they don't give the same results? Does the first method write the variables in the order they are declared in the structure or in some other order? I should say that I've simplified my problem for this example - I have 7 variables or different types in my structure.


21-06-2004, 01:59 PM
Take a look at this source to test the problem
You'll see that the size of the structure as a whole differs from the size of the total size of the variables inside it! However, if you change the variables in the structure to all byte's then it works because the sizes are the same for some reason. Why does the size differ when there are non byte variables in the structure?

21-06-2004, 02:21 PM
Record field alignment. Look up $A switch in help

21-06-2004, 04:12 PM
ok - thanks.
It's completely mucked up my backwards compatibility!

21-06-2004, 04:35 PM
Always use PACKED directive when define records that are going to be used with stream, blockread/blockwrite or any similar acces way.

TStructure = packed record
variable1 : byte;
variable2 : Single;

the packed directive will asure that the record size will be the sum of all their fields, otherwise the compiler could add internal dumy bytes if neccesary to force the structure size get alway word aligned for fast accesing.