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

后端 未结 3 1703
深忆病人
深忆病人 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:35

    With modern .NET, you can use spans for this:

    var bytes = MemoryMarshal.Cast<Color32, byte>(colors);
    

    This gives you a Span<byte> that covers the same data. The API is directly comparable to using vectors (byte[]), but it isn't actually a vector, and there is no copy: you are directly accessing the original data. It is like an unsafe pointer coercion, but: entirely safe.

    If you need it as a vector, ToArray and copy methods exist for that.

    0 讨论(0)
  • 2020-12-06 13:40

    Well why do you work with Color32?

    byte[] Bytes = tex.GetRawTextureData(); . . . Tex.LoadRawTextureData(Bytes); Tex.Apply();

    0 讨论(0)
  • 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.

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