How to convert a structure to a byte array in C#?

前端 未结 14 1160
难免孤独
难免孤独 2020-11-22 09:59

How do I convert a structure to a byte array in C#?

I have defined a structure like this:

public struct CIFSPacket
{
    public uint protocolIdentifi         


        
14条回答
  •  佛祖请我去吃肉
    2020-11-22 10:26

    As the main answer is using CIFSPacket type, which is not (or no longer) available in C#, I wrote correct methods:

        static byte[] getBytes(object str)
        {
            int size = Marshal.SizeOf(str);
            byte[] arr = new byte[size];
            IntPtr ptr = Marshal.AllocHGlobal(size);
    
            Marshal.StructureToPtr(str, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
    
            return arr;
        }
    
        static T fromBytes(byte[] arr)
        {
            T str = default(T);
    
            int size = Marshal.SizeOf(str);
            IntPtr ptr = Marshal.AllocHGlobal(size);
    
            Marshal.Copy(arr, 0, ptr, size);
    
            str = (T)Marshal.PtrToStructure(ptr, str.GetType());
            Marshal.FreeHGlobal(ptr);
    
            return str;
        }
    

    Tested, they work.

提交回复
热议问题