Convert a byte array to a class containing a byte array in C#

Posted by Mathijs on Stack Overflow See other posts from Stack Overflow or by Mathijs
Published on 2010-05-02T23:16:08Z Indexed on 2010/05/02 23:17 UTC
Read the original article Hit count: 455

Filed under:
|
|
|
|

I've got a C# function that converts a byte array to a class, given it's type:

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

I use sequential structs:

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

This worked fine, until I tried to convert to a struct/class containing a byte array.

[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 Marshal.PtrToStructure to fail with the following error:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I'm guessing that using a fixed array would be a solution, but can it also be done without having to resort to unsafe code?

© Stack Overflow or respective owner

Related posts about c#

Related posts about marshalling