Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice
  2. Enter the 2020.2 Beta Sweepstakes for a chance to win an Oculus Quest 2.
    Dismiss Notice

[solved] How correctly use MemCpy, to copy NativeArray <Matrix4x4> to Matrix4x4 []?

Discussion in 'Data Oriented Technology Stack' started by Antypodish, Oct 14, 2019.

  1. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    7,563
    I know I asked pretty much same question here
    https://forum.unity.com/threads/entity-highlighting-in-jobs-material-uv-atlas-shader.745190/
    but I think this question deserves dedicated attention, in own thread.
    And since I am such noob using pointers, therefore my question.

    So if I got NativeArray <Matrix4x4> or NativeArray <float4x4>, how to copy it to Matrix4x4?
    As far I understand, this is called copying native to managed data.
    Obviously using 'for loop' works. But is slow for large arrays.
    I tried using MemCpy, but at best so far I managing crash Unity :)

    I have noticed that NativeArray <Matrix4x4> has GetUnsafePtr. But even using it, results no avail.

    Best I was able to get, is
    Code (CSharp):
    1. unsafe
    2. {
    3.     var arrayOfMatrices4x4 = (byte*)  ( UnsafeUtility.SizeOf <Matrix4x4> () * nativeArrayOfMatrices4x4.Length  ) ;              
    4.     UnsafeUtility.MemCpy ( arrayOfMatrices4x4, nativeArrayOfMatrices4x4.GetUnsafePtr <Matrix4x4> (), nativeArrayOfMatrices4x4.Length );
    5. }
    I am pretty sure sure thats wrong. Even if I replace nativeArrayOfMatrices4x4.Length for 1, still got crashes.


    Any thoughts on guidance?
     
  2. recursive

    recursive

    Joined:
    Jul 12, 2012
    Posts:
    651
    I think you also need to pin the managed array for the duration of the copy.
     
  3. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    2,547
    Doesn't NativeArray have a CopyTo(T[] array) method built in?
     
  4. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    7,563
    Oh me daft. Indeed. :oops:
    And works for what I needed.

    Just side question, any functional difference between
    CopyTo (T[] array)
    and
    T[] array = ... ToArray () ?
    Both output same, form what I see. Other than that, in first case array size need to be preallocated.

    Thx as usual.
     
  5. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    2,547
    CopyTo lets you reuse an array so you don't have to keep creating allocations.
     
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    7,563
    Ah, good to know. so I will use CopyTo.
     
unityunity