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

前端 未结 14 1147
难免孤独
难免孤独 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:15

    @Abdel Olakara answer donese not work in .net 3.5, should be modified as below:

        public static void ByteArrayToStructure(byte[] bytearray, ref T obj)
        {
            int len = Marshal.SizeOf(obj);
            IntPtr i = Marshal.AllocHGlobal(len);
            Marshal.Copy(bytearray, 0, i, len);
            obj = (T)Marshal.PtrToStructure(i, typeof(T));
            Marshal.FreeHGlobal(i);
        }
    

提交回复
热议问题