How to arrange structures with unknown strings of string length in C #

I get an array of bytes, I need to decouple it with C # struct. I know the type of structure, it has several lines. The lines in the byte array look like this: the first two bytes are the length of the string, and then the string itself. I do not know the length of the strings. I know its unicode!

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public class User { int Id;//should be 1 String UserName;//should be OFIR String FullName;//should be OFIR } 

an array of bytes looks like this: 00,00,01,00, 00,00,08,00, 4F, 00,46,00,49,00,52,00, 00,00,08,00, 4F, 00,46 , 00.49.00.52.00,

I also found this link with the same problem: loading binary data into a structure

Thanks to everyone, Ophir

+8
c # struct marshalling unmarshalling
source share
2 answers

I would do it using BinaryReader . This will go as follows:

 Foo ReadFoo(Byte[] bytes) { Foo foo = new Foo(); BinaryReader reader = new BinaryReader(new MemoryStream(bytes)); foo.ID = reader.ReadUInt32(); int userNameCharCount = reader.ReadUInt32(); foo.UserName = new String(reader.ReadChars(userNameCharCount)); int fullNameCharCount = reader.ReadUInt32(); foo.FullName = new String(reader.ReadChars(fullNameCharCount)); return foo; } 

Note that this will not work directly for the byte array example you provided. The char number and the identifier field do not correspond to standard small ordinal or bendian orders. It may be that the fields are 16 bits and that they are added with 16-bit padding fields. Who created this thread?

But the exact format is not too important for this strategy, since you can just change ReadInt32 to ReadInt16 , reorder them, whatever, to make it work.

I do not like serializer attributes. This is because it associates your internal data structures with how it exchanges. This is interrupted if you need to support multiple versions of dataformat.

+3
source share

This is not an answer (yet), but it is a question / comment with lots of code for feedback. How do you interpret an array of bytes? Smash it.

 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct Foo { public int id; //[MarshalAs(UnmanagedType.BStr)] //public string A; //[MarshalAs(UnmanagedType.BStr)] //public string B; } static void Main(string[] args) { byte[] bits = new byte[] { 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, // Length prefix? 0x4F, 0x00, // Start OFIR? 0x46, 0x00, 0x49, 0x00, 0x52, 0x00, 0x00, 0x00, 0x08, 0x00, // Length prefix? 0x4F, 0x00, // Start OFIR? 0x46, 0x00, 0x49, 0x00, 0x52, 0x00 }; GCHandle pinnedPacket = GCHandle.Alloc(bits, GCHandleType.Pinned); Foo msg = (Foo)Marshal.PtrToStructure( pinnedPacket.AddrOfPinnedObject(), typeof(Foo)); pinnedPacket.Free(); } 
0
source share

All Articles