我有一个 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/