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

前端 未结 5 1870
逝去的感伤
逝去的感伤 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条回答
  •  Happy的楠姐
    2020-12-16 22:22

    This code requires unsafe switch but should be fast. I think you should benchmark these answers...

    var bytes = new byte[] { 1, 2, 3, 4 };
    
    var colors = MemCopyUtils.ByteArrayToColor32Array(bytes);
    

    public class MemCopyUtils
    {
        unsafe delegate void MemCpyDelegate(byte* dst, byte* src, int len);
        static MemCpyDelegate MemCpy;
    
        static MemCopyUtils()
        {
            InitMemCpy();
        }
    
        static void InitMemCpy()
        {
            var mi = typeof(Buffer).GetMethod(
                name: "Memcpy",
                bindingAttr: BindingFlags.NonPublic | BindingFlags.Static,
                binder:  null,
                types: new Type[] { typeof(byte*), typeof(byte*), typeof(int) },
                modifiers: null);
            MemCpy = (MemCpyDelegate)Delegate.CreateDelegate(typeof(MemCpyDelegate), mi);
        }
    
        public unsafe static Color32[] ByteArrayToColor32Array(byte[] bytes)
        {
            Color32[] colors = new Color32[bytes.Length / sizeof(Color32)];
    
            fixed (void* tempC = &colors[0])
            fixed (byte* pBytes = bytes)
            {
                byte* pColors = (byte*)tempC;
                MemCpy(pColors, pBytes, bytes.Length);
            }
            return colors;
        }
    }
    

提交回复
热议问题