Search Unity

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

Discussion in 'Entity Component System' started by Antypodish, Oct 14, 2019.

  1. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    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:
    669
    I think you also need to pin the managed array for the duration of the copy.
     
  3. tertle

    tertle

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

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    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:
    3,759
    CopyTo lets you reuse an array so you don't have to keep creating allocations.
     
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,769
    Ah, good to know. so I will use CopyTo.
     
  7. chadfranklin47

    chadfranklin47

    Joined:
    Aug 11, 2015
    Posts:
    226
    Last edited: Feb 26, 2022
    Antypodish likes this.