0

Original question: C# array within a struct

Fixed size buffers work for some intrinsic data types(bool,byte,short,int,..), but when needing to define an array of struct, within a struct, I've so far failed to be clever enough.

In the following, assume 'recordLayout' is a struct containing 18 fields, including some arrays of simple types, which were solved by unsafe and fixed size buffers. Next I'm needing to populate the following structure (containing an array of struct) from the binary file.

[StructLayout(LayoutKind.Sequential,Pack=1)]
unsafe struct dataBlock {               // 2048 bytes
    fixed ushort junk[5];
    fixed recordLayout records[22];     // doesnt work of course, data type constrained
    fixed byte filler[14];
}

I've tried creating an explicit LayoutKind struct that maps a fixed byte array to the record array, but immediately bump into not being allowed to do that.

Community
  • 1
  • 1
Robert Kerr
  • 1,257
  • 2
  • 17
  • 33
  • 1
    Why don't you use built in binary serialization? Seems like you are trying to recreate something that already exists. – Ed S. Jan 02 '12 at 20:21
  • Can binary deserialization read data file structures written with C? I haven't used serialization/deserialization but thought it was about writing and reading .NET objects to file. I think you're suggesting I can deserialize the above example C data file? – Robert Kerr Jan 02 '12 at 20:28
  • I think what @EdS. was trying to say was to use the built in deserializer to load an instance of your struct from a file, and then save it as well. – annonymously Jan 02 '12 at 20:33
  • The question is that I'm unable to define the struct in the first place, since it contains an array of a struct. – Robert Kerr Jan 02 '12 at 20:35
  • There's no recursion. The contained array is a different struct type. – Robert Kerr Jan 02 '12 at 20:42
  • ah, I missed that, sorry – annonymously Jan 02 '12 at 20:42
  • 1
    The question you linked to already provides the solution: Don't try to map the whole layout to a struct, just read the fields and arrays individually. You even accepted that solution - in how far is this question different? – ChrisWue Jan 02 '12 at 21:31
  • This question was about struct array within a struct; other question was only array in struct; and people answered showing how to use fixed with basic types. Since those answers weren't wrong, I posted this new question. Only afterwards did CodeinChaos post a solution that answered both parts, and I accepted it. So while I still don't know how to declare an array of struct in struct, my actual problem was solved using a different approach as accepted in other question. – Robert Kerr Jan 02 '12 at 22:09

0 Answers0