I have a file containing binary data with a format that matches this struct:
struct MyStruct {
UInt32 count;
UInt32[] items;
}
The binary data can be any length as there can be any number of items, but the number of items is defined in count. Using Marshal.PtrToStructure
doesn't seem to allow for this binary format, where there is a variable number of items? Using Attributes you can set the size of the array of items, but this has to be a constant, is there no way to tell it to look in count
while its reading the data?
I've thought of defining the format in XML, and using it to read into the struct with my own code, but this would be a lot of duplicate data, if the file format changed, I'd have to change the XML and struct, rather than just the struct.
And I've thought of using a custom Attribute on the items
field, and writing my own code to read in the data but in order to enumerate through the struct's fields I'd have to use Reflection? which is slow?
(Also I could read it myself manually, but I've trimmed the struct down for the question, and like to not have to change the reading code if the structure changes)
MyStruct
can be done in a single line:List<MyStruct> data = (List<MyStruct>) new XmlSerializer(typeof(List<MyStruct>)).Deserialize(File.OpenText("MyStructs.xml"));
– Mr. Smith Apr 21 at 0:59