6

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?

2
  • Could you use a binary serializer/deserializer instead? mikehadlow.blogspot.com/2006/11/… Commented May 2, 2010 at 23:22
  • Can you give a little more background to what you are doing? If possible, using the built-in serialization classes will save you a lot of headache. Commented May 2, 2010 at 23:29

2 Answers 2

6

No need for unsafe code:

[StructLayout(LayoutKind.Sequential)]
public struct PacketFormat
{
  public byte header;
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public byte[] data;
}
Sign up to request clarification or add additional context in comments.

Comments

4

You need to use a fixed size byte array.

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

1 Comment

My question was whether it could be done without unsafe code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.