加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:18:18 所属栏目:百科 来源:网络整理
导读:我有一个C#函数将字节数组转换为类,给定它的类型: IntPtr buffer = Marshal.AllocHGlobal(rawsize);Marshal.Copy(data,buffer,rawsize);object result = Marshal.PtrToStructure(buffer,type);Marshal.FreeHGlobal(buffer); 我使用顺序结构: [StructLayout
我有一个C#函数将字节数组转换为类,给定它的类型:
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(data,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];
}

Marshal.SizeOf(type)返回16,它太低(应该是257)并导致Marshal.PtrToStructure失败并出现以下错误:

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

我猜测使用固定阵列是一种解决方案,但它是否可以在不必诉诸不安全代码的情况下完成?

解决方法

不需要不安全的代码:
[StructLayout(LayoutKind.Sequential)]
public struct PacketFormat
{
  public byte header;
  [MarshalAs(UnmanagedType.ByValArray,SizeConst = 256)] public byte[] data;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读