Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

byte[] to NativeArray

Discussion in 'Scripting' started by sylde, Mar 1, 2021.

  1. sylde

    sylde

    Joined:
    Sep 21, 2018
    Posts:
    3
    Hi,
    I wonder why this is a fail:
    Code (CSharp):
    1.  
    2.         byte[] a = new byte[93];
    3.         unsafe
    4.         {
    5.             fixed (byte* p = &a[0])
    6.             {
    7.                 NativeArray<byte> na = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(p, a.Length, Allocator.None);
    8.                 var b = na[0];// Fails with NullReferenceException
    9.             }
    10.         }
    11.  
    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?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    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://forum.unity.com/threads/texture-byte-per-pixel.624343/#post-4185943

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

    sylde

    Joined:
    Sep 21, 2018
    Posts:
    3
    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...
     
  4. andrew-lukasik

    andrew-lukasik

    Joined:
    Jan 31, 2013
    Posts:
    249
    A pointer for anyone else who is still looking for the answer to this: https://forum.unity.com/threads/nat...array-throws-exceptions.1330899/#post-8409792


    Code (CSharp):
    1. var nativeArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(ptr, array.Length, Allocator.None);
    2. #if ENABLE_UNITY_COLLECTIONS_CHECKS
    3. NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeArray, AtomicSafetyHandle.GetTempMemoryHandle());
    4. #endif