How to convert complex struct into Span<byte>? And how about reverse? #72758
-
I'm looking for a faster way to serialize and deserialize stream and binary. But for complex struct, I'm stuck. Sample struct here:
The sample data here:
I have tried
What should I do? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
As the exception message says, |
Beta Was this translation helpful? Give feedback.
-
You cannot treat a managed structure (one containing |
Beta Was this translation helpful? Give feedback.
-
As a side note - while you can pack and blit on single byte boundaries, there's usually a performance penalty for doing unaligned (that is, not aligned to the native word size) operations. Unless you're explicitly mimicking an existing protocol or file type, you may want to reorder fields. |
Beta Was this translation helpful? Give feedback.
-
Instead of using structs should these be classes, and for Type <-> Span having a serializer? PS: with the struct, and when the array length is known in advance, then you could use fixed sized buffers. |
Beta Was this translation helpful? Give feedback.
You cannot treat a managed structure (one containing
ref
s, classes, arrays, etc) as a sequence of bytes and write it to a file, because managed types are not blittable. Arrays,string
s, etc are not stored inline in the structure, they are GC-tracked pointers to data on the managed heap. They will have no meaning once they are written to disk. I would suggest using an existing binary serialization framework when you have a complex scenario like this.