简体   繁体   English

如何将结构写入现有的字节数组?

[英]How to write a struct to a pre existing byte array?

I've seen lots of examples of how to convert a struct to a byte array by creating a new byte array. 我已经看到了许多有关如何通过创建新的字节数组将结构转换为字节数组的示例。

But i am trying to avoid this. 但是我正在努力避免这种情况。 I have a message buffer of byte[1024] and i want to write my struct to this byte array from index 1 onwards. 我有一个字节[1024]的消息缓冲区,我想从索引1开始将结构写入此字节数组。 Index 0 is the header so i skip that one. 索引0是标题,所以我跳过了那个。

I can't find any examples of this is done without creating a new byte array. 如果没有创建新的字节数组,就找不到完成此操作的任何示例。 Is this even possible ? 这有可能吗?

How i currently convert objects to byte arrays: 我目前如何将对象转换为字节数组:

    public static byte[] GetBytes<T>(T data)
    {
        int size = Marshal.SizeOf(data);
        byte[] arr = new byte[size];
        IntPtr ptr = Marshal.AllocHGlobal(size);

        Marshal.StructureToPtr(data, ptr, true);
        Marshal.Copy(ptr, arr, 0, size);
        Marshal.FreeHGlobal(ptr);

        return arr;
    }

The problem with this is its writing the object on a new array at index 0. I need to apply it to index 1 onwards. 问题是它将对象写到索引为0的新数组上。我需要将其应用于索引1以后。 Where index 0 will designate the size of struct in bytes. 索引0将以字节为单位指定结构的大小。

Using your existing code as an example, in order to copy your struct bytes to an existing array at position 1, just pass the existing array and the start position of 1 to Marshal.Copy : 以您现有的代码为例,要将结构字节复制到位置1的现有数组,只需将现有数组和起始位置1传递给Marshal.Copy

byte[] existingArray = new byte[1024];      // This is your existing 1024 size byte array

int size = Marshal.SizeOf(data);
IntPtr ptr = Marshal.AllocHGlobal(size);

Marshal.StructureToPtr(data, ptr, true);
Marshal.Copy(ptr, existingArray, 1, size);  // Pass your array and start at position 1
Marshal.FreeHGlobal(ptr);]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM