Unmanaged byte array to managed structure I have a need to turn byte arrays into various structures.

First version:

public static object ConvertBytesToStructure(object target, byte[] source, Int32 targetSize, int startIndex, int length)
    {
        if (target == null)
            return null;

        IntPtr p_objTarget = Marshal.AllocHGlobal(targetSize);
        try
        {
            Marshal.Copy(source, startIndex, p_objTarget, length);
            Marshal.PtrToStructure(p_objTarget, target);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            Marshal.FreeHGlobal(p_objTarget);
        }

        return target;
    }


I have found that when i calling to the first version a lot of times in a second - i getting poor performance.

So i trying to improve that to the version 2:

  private static T ReadUsingMarshalUnsafe&lt;T&gt;(byte[] data, int startIndex, int length)
        {
            byte[] fixedData = new byte[length];
            unsafe
            {
                fixed (byte* pSource = data, pTarget = fixedData)
                {
                    int index = 0;
                    for (int i = startIndex; i &lt; data.Length; i++)
                    {
                        pTarget[index] = pSource[i];
                        index++;
                    }
                }

                fixed (byte* p = &amp;fixedData[0])
                {
                    return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
                }
            }
        }


I have found that this version getting very good performance..

But i want to getting your code review - maybe i'll have any memory leak? maybe i can to do this with efficent another way?

Thanks!
Expanding on my comment; below you'll find a very simple program that compares the method I suggested with your original example. The results on my machine show that the MemoryMarshal class is about 85x faster. You might want to experiment a bit and try running a similar test with a larger struct; maybe your method is faster for the specific problem that you're trying to solve.

Comparison Code:

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Runtime.InteropServices;

public readonly struct SomeStruct
{
    private readonly ulong m_x;
    private readonly ulong m_y;
    private readonly ulong m_z;

    public ulong X =&gt; m_x;
    public ulong Y =&gt; m_y;
    public ulong Z =&gt; m_z;

    public SomeStruct(ulong x, ulong y, ulong z) {
        m_x = x;
        m_y = y;
        m_z = z;
    }
}

public class Race
{
    private readonly byte[] m_data = new byte[] {
        0, 0, 0, 0, 0, 0, 0, 0,
        1, 0, 0, 0, 0, 0, 0, 0,
        1, 255, 0, 0, 0, 0, 0, 0,
    };

    [Benchmark(Baseline = true)]
    public SomeStruct A() =&gt; MemoryMarshal.Read&lt;SomeStruct&gt;(m_data);
    [Benchmark]
    public SomeStruct B() =&gt; Program.ReadUsingMarshalUnsafe&lt;SomeStruct&gt;(m_data, 0, m_data.Length);
}

class Program
{
    static void Main(string[] args) {
        var summary = BenchmarkRunner.Run&lt;Race&gt;();

        Console.ReadKey();
    }

    public static T ReadUsingMarshalUnsafe&lt;T&gt;(byte[] data, int startIndex, int length) {
        byte[] fixedData = new byte[length];
        unsafe {
            fixed (byte* pSource = data, pTarget = fixedData) {
                int index = 0;
                for (int i = startIndex; i &lt; data.Length; i++) {
                    pTarget[index] = pSource[i];
                    index++;
                }
            }

            fixed (byte* p = &amp;fixedData[0]) {
                return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
            }
        }
    }
}



BenchmarkDotNet Results: