Convert byte array to class containing byte array in C #

I have a C # function that converts a byte array into a class, given its type:

IntPtr buffer = Marshal.AllocHGlobal(rawsize); Marshal.Copy(data, 0, buffer, rawsize); object result = Marshal.PtrToStructure(buffer, type); Marshal.FreeHGlobal(buffer); 

I use sequential structures:

 [StructLayout(LayoutKind.Sequential)] public new class PacketFormat : Packet.PacketFormat { } 

This worked fine until I tried to convert to a struct / class containing an array of bytes.

 [StructLayout(LayoutKind.Sequential)] public new class PacketFormat : Packet.PacketFormat { public byte header; public byte[] data = new byte[256]; } 

Marshal.SizeOf(type) returns 16, which is too low (should be 257) and causes a Marshal.PtrToStructure error with the following error:

Attempted to read or write protected memory. This often indicates that another memory is corrupted.

I assume that using a fixed array will be a solution, but is it possible to do this without using unsafe code?

+6
c # struct serialization
source share
2 answers

No need for unsafe code:

 [StructLayout(LayoutKind.Sequential)] public struct PacketFormat { public byte header; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public byte[] data; } 
+5
source share

You need to use a fixed size byte array.

 [StructLayout(LayoutKind.Sequential)] public unsafe struct PacketFormat { public byte header; public fixed byte data[256]; } 
+4
source share

All Articles