C# 将字节数组转换为包含C中字节数组的类#

C# 将字节数组转换为包含C中字节数组的类#,c#,serialization,struct,C#,Serialization,Struct,我有一个C#函数,可以将字节数组转换为类,给定它的类型: IntPtr buffer = Marshal.AllocHGlobal(rawsize); Marshal.Copy(data, 0, buffer, rawsize); object result = Marshal.PtrToStructure(buffer, type); Marshal.FreeHGlobal(buffer); 我使用顺序结构: [StructLayout(LayoutKind.Sequential)] pub

我有一个C#函数,可以将字节数组转换为类,给定它的类型:

IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(data, 0, buffer, rawsize);
object result = Marshal.PtrToStructure(buffer, type);
Marshal.FreeHGlobal(buffer);
我使用顺序结构:

[StructLayout(LayoutKind.Sequential)]
public new class PacketFormat : Packet.PacketFormat { }
在我尝试转换为包含字节数组的结构/类之前,这种方法工作得很好

[StructLayout(LayoutKind.Sequential)]
public new class PacketFormat : Packet.PacketFormat
{
  public byte header;
  public byte[] data = new byte[256];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct PacketFormat
{
  public byte header;
  public fixed byte data[256];
}
Marshal.SizeOf(type)
返回16,该值太低(应为257),并导致
Marshal.PtrToStructure
失败,出现以下错误:

试图读取或写入受保护的内存。这通常表示其他内存已损坏


我猜想使用固定数组将是一个解决方案,但它也可以在不使用不安全代码的情况下完成吗?

您需要使用固定大小的字节数组

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

不需要不安全代码:

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

你能改用二进制序列化器/反序列化器吗?你能给我一点你正在做的事情的背景吗?如果可能的话,使用内置的序列化类将为您省去很多麻烦。我的问题是,是否可以在没有不安全代码的情况下完成。