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

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

    If you really want it to be FAST on Windows, you can do it using unsafe code with CopyMemory. CopyMemory is about 5x faster (e.g. 800MB of data takes 3s to copy via marshalling, while only taking .6s to copy via CopyMemory). This method does limit you to using only data which is actually stored in the struct blob itself, e.g. numbers, or fixed length byte arrays.

        [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
        private static unsafe extern void CopyMemory(void *dest, void *src, int count);
    
        private static unsafe byte[] Serialize(TestStruct[] index)
        {
            var buffer = new byte[Marshal.SizeOf(typeof(TestStruct)) * index.Length];
            fixed (void* d = &buffer[0])
            {
                fixed (void* s = &index[0])
                {
                    CopyMemory(d, s, buffer.Length);
                }
            }
    
            return buffer;
        }
    
    0 讨论(0)
  • 2020-11-22 10:39
            Header header = new Header();
            Byte[] headerBytes = new Byte[Marshal.SizeOf(header)];
            Marshal.Copy((IntPtr)(&header), headerBytes, 0, headerBytes.Length);
    

    This should do the trick quickly, right?

    0 讨论(0)
提交回复
热议问题