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

前端 未结 14 1034
难免孤独
难免孤独 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;
        }
    

提交回复
热议问题