Copy array to struct array as fast as possible in C#

前端 未结 5 1876
逝去的感伤
逝去的感伤 2020-12-16 21:24

I am working with Unity 4.5, grabbing images as bytes arrays (each byte represent a channel, taking 4 bytes per pixel (rgba) and displaying them on a texture converting the

5条回答
  •  孤城傲影
    2020-12-16 22:02

    Yes, Marshal.Copy is the way to go. I've answered a similar question here.

    Here's a generic method to copy from struct[] to byte[] and vice versa

    private static byte[] ToByteArray(T[] source) where T : struct
    {
        GCHandle handle = GCHandle.Alloc(source, GCHandleType.Pinned);
        try
        {
            IntPtr pointer = handle.AddrOfPinnedObject();
            byte[] destination = new byte[source.Length * Marshal.SizeOf(typeof(T))];
            Marshal.Copy(pointer, destination, 0, destination.Length);
            return destination;
        }
        finally
        {
            if (handle.IsAllocated)
                handle.Free();
        }
    }
    
    private static T[] FromByteArray(byte[] source) where T : struct
    {
        T[] destination = new T[source.Length / Marshal.SizeOf(typeof(T))];
        GCHandle handle = GCHandle.Alloc(destination, GCHandleType.Pinned);
        try
        {
            IntPtr pointer = handle.AddrOfPinnedObject();
            Marshal.Copy(source, 0, pointer, source.Length);
            return destination;
        }
        finally
        {
            if (handle.IsAllocated)
                handle.Free();
        }
    }
    

    Use it as:

    [StructLayout(LayoutKind.Sequential)]
    public struct Demo
    {
        public double X;
        public double Y;
    }
    
    private static void Main()
    {
        Demo[] array = new Demo[2];
        array[0] = new Demo { X = 5.6, Y = 6.6 };
        array[1] = new Demo { X = 7.6, Y = 8.6 };
    
        byte[] bytes = ToByteArray(array);
        Demo[] array2 = FromByteArray(bytes);
    }
    

提交回复
热议问题