简体   繁体   中英

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. Index 0 is the header so i skip that one.

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. Where index 0 will designate the size of struct in bytes.

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 :

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);]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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