将struct转换为字节数组

本文关键字:字节数 数组 字节 struct 转换 | 更新日期: 2023-09-27 18:09:44

我读了下面的一些地方。谁能举个例子给我解释一下呢

消息甚至可以是一个结构体,它被转换成一个字节数组,在调试UART上输出。

然后在PC端,传入的字节数组可以很容易地转换回类似struct的对象。

将struct转换为字节数组

您可以使用unsafe作为字节指针访问任何位元表(数组,字符串,结构体等)类型。

值类型的局部变量不需要固定:

public unsafe void ReadAsBytePointer(MyStruct obj)
{
    byte* ptr = (byte*)&obj;
    ...    
}

数组必须固定。最简单的解决方案是使用fixed:

public unsafe void ReadAsBytePointer(MyStruct[] input)
{
    fixed(MyStruct* ptr = input)
    {
        byte* byteArray = (byte*)ptr;
    }
}

对于一般情况,不需要在代码中添加unsafe,您可以使用GCHandle:

static byte[] GetBytes<T>(T input)
  where T : struct
{
    int size = Marshal.SizeOf(typeof(T));
    byte[] result = new byte[size];
    GCHandle gc = GCHandle.Alloc(input, GCHandleType.Pinned);
    try
    {
        Marshal.Copy(gc.AddrOfPinnedObject(), result, 0, size);
    }
    finally
    {
        gc.Free();
    }
    return result;
}