gpt4 book ai didi

c# - 错误 : The specified structure must be blittable or have layout information

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:41 26 4
gpt4 key购买 nike

public class TestSerializer
{
public static byte[] StructureToByteArray(Test[] array)
{
int size = Marshal.SizeOf(array.Length);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(array, ptr, true);//error
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}

当我写上面的代码时,我得到了这个错误。但是我的结构是这样的:

public struct Test
{
[FieldOffset(0)]
// public string name;

public Byte icode;

[FieldOffset(1)]
public Byte method;

[FieldOffset(2)]
public Byte wav;

[FieldOffset(3)]
public Byte wav2;

[FieldOffset(4)]
public Byte unit;

[FieldOffset(5)]
public Byte temp;
[fieldOffset(6)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] itemname;

//public float factor;
}

Test[] array = new Test[200];

我想将这个“数组”转换为字节数组,但我对以下行也有疑问

int size = Marshal.SizeOf(array.Length);

有没有可能像这样写

数组[1].itemname=asd;

最佳答案

尝试将属性 [StructLayout(LayoutKind.Explicit)] 添加到您的 struct test

Marshal.SizeOf(array.Length) 解析为 Marshal.SizeOf(200) - 200 是一个 int32,为此报告大小为 4。您需要执行 array.Length * Marshal.SizeOf(typeof (测试))

问题是 Test 类型的数组不可 blittable according to the documentation (虽然结构本身是,但如果您用 [StructLayout(LayoutKind.Explicit)]LayoutKind.Sequential 标记它)并且您需要自己在循环。

public static byte[] StructureToByteArray(Test[] array)
{
int structSize = Marshal.SizeOf(typeof(Test));
int size = array.Length * structSize;
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
for (int i = 0; i < array.Length; i++ )
Marshal.StructureToPtr(array[i], ptr+i*structSize, true);//error
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}

数组必须以 4 字节边界开始,因此结构应如下所示:

[StructLayout(LayoutKind.Explicit)]
public struct Test
{
[FieldOffset(0)]
public byte icode;

[FieldOffset(1)]
public byte method;

[FieldOffset(2)]
public byte wav;

[FieldOffset(3)]
public byte wav2;

[FieldOffset(4)]
public byte unit;

[FieldOffset(5)]
public byte temp;

[FieldOffset(8)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] itemname;
}

字符串分配可以通过将字符串编码为字节数组并复制到结构中来完成,如下所示:

 Test[] array = new Test[200];
byte[] temp = Encoding.UTF8.GetBytes("asd");
array[0].itemname = new byte[20];
Array.Copy(temp, array[0].itemname, temp.Length);

关于c# - 错误 : The specified structure must be blittable or have layout information,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25439983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com