Can a NativeArray be construed from stackalloc memory?

I am trying to stackalloc some memory; and use it as a NativeArray like this:

[StructLayout(LayoutKind.Sequential)]
public struct Vertex : IComparable<Vertex>
{
    public readonly static int Size = UnsafeUtility.SizeOf<Vertex>();
    public float2 Point;
    public float2 Comparend;
    public int CompareTo(Vertex other)
    {
        var diff = Comparend.x - other.Comparend.x;
        return diff == 0 ? 0 : diff > 0 ? 1 : -1;
    }
}
public void SomeFunction()
{
    var n = H.Length;
    byte* stackB = stackalloc byte[n * Vertex.Size];
    var a= NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vertex>(stackB ,n, Allocator.None);
    //pop some data
    a.Sort();
}

Is it safe to use it this way? Is the NativeArray okay without safety handle?

stackB will be automatically deleted from stack when the function is exited. As long as you don’t return the array there shouldn’t be a problem.

1 Like

Greate that exactly what I am expecting. I just want to use Sort function from NativeArray. I am using stackB directly in other parts.

NativeArray just grants the access to a memory block, just like Span. I have tried both stackalloc and Sort() in jobs, pay attention that Sort will perform poorly when more elements are added (i.e 250+ elements). Also instead of allocating memory all the time you could just have a preallocated memory block via Malloc and just pass its pointer to a job and do the same thingy with ConvertExistingDataToNativeArray. Don’t forget AtomicSafetyHandle though or you will get null ref.