Fast copy of Color32[] array to byte[] array

后端 未结 3 1707
深忆病人
深忆病人 2020-12-06 13:07

What would be a fast method to copy/convert an array of Color32[] values to a byte[] buffer? Color32 is

3条回答
  •  爱一瞬间的悲伤
    2020-12-06 13:51

    I ended up using this code:

    using System.Runtime.InteropServices;
    
    private static byte[] Color32ArrayToByteArray(Color32[] colors)
    {
        if (colors == null || colors.Length == 0)
            return null;
    
        int lengthOfColor32 = Marshal.SizeOf(typeof(Color32));
        int length = lengthOfColor32 * colors.Length;
        byte[] bytes = new byte[length];
    
        GCHandle handle = default(GCHandle);
        try
        {
            handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
            IntPtr ptr = handle.AddrOfPinnedObject();
            Marshal.Copy(ptr, bytes, 0, length);
        }
        finally
        {
            if (handle != default(GCHandle))
                handle.Free();
        }
    
        return bytes;
    }
    

    Which is fast enough for my needs.

提交回复
热议问题