Results 1 to 5 of 5

Thread: Stream writing problem

  1. #1

    Stream writing problem

    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.

    [pascal]TStructure = record
    variable1 : byte;
    variable2 : Single;
    end;

    var
    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));[/pascal]

    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.

    Peter

  2. #2

    Stream writing problem

    Take a look at this source to test the problem
    http://atlas.walagata.com/w/peterbon...retostream.zip
    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?
    Peter

  3. #3

    Stream writing problem

    Record field alignment. Look up $A switch in help

  4. #4

    Stream writing problem

    ok - thanks.
    It's completely mucked up my backwards compatibility!

  5. #5

    re-

    Always use PACKED directive when define records that are going to be used with stream, blockread/blockwrite or any similar acces way.

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

    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.


    tp.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •