byte[] to NativeArray

Hi,
I wonder why this is a fail:

        byte[] a = new byte[93];
        unsafe
        {
            fixed (byte* p = &a[0])
            {
                NativeArray<byte> na = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(p, a.Length, Allocator.None);
                var b = na[0];// Fails with NullReferenceException
            }
        }

Documentation states that “Allocator.None can be used in case the data is owned externally, while the others can be used to transfer control to the NativeArray”.
Can’t we share memory fixed in the heap with Unity’s C++ functions?

I’m not sure of your specific attempt at interoperability, but when I try to pin and pass memory to my native code, this is the pattern I use:

Pinning a texture for manipulation via native code:
https://discussions.unity.com/t/731131/6

The above example is an array of Color32[ ] but I imagine the same process would work with any datatype.

Thanks for the sample code…

I’d like to use Mesh.SetVertices(NativeArray), to avoid unnecessary memory copy and allocation.
I have my vertices in the heap in a Vector3[ ], I pin it, and hope I can use NativeArrayUnsafeUtility to share the buffer with the C++ side.

Unsuccessfully until now. Mesh.SetVertices(NativeArray) fails with the same NullReferenceException as var b = na[0] in my example…

A pointer for anyone else who is still looking for the answer to this: NativeArray created with NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray throws exceptions - Unity Engine - Unity Discussions

var nativeArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(ptr, array.Length, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeArray, AtomicSafetyHandle.GetTempMemoryHandle());
#endif