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

标签 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)]
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;
}

关于c# - 在 C# 中将字节数组转换为包含字节数组的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2755398/

相关文章:

c# - 2 兄弟嵌套 transactionScope 给出 : the Transaction has aborted

c# - 通过 C# 获取网站证书

c# - 为什么我编译的 AutoIt 脚本在从 C# 调用时无法返回?

c# - Winforms 插件架构中的 IOC

c - 使用 GNU 程序集访问指向结构的 *next 指针

struct - 无法在golang中包含多个文件

jQuery 序列化不会在嵌套 div 中选取 select 标签

scala - Spark : Writing to Avro file

java.io.StreamCorruptedException : invalid stream header: 7371007E

c++ - 指针函数参数数组 - 奇怪的行为