Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Discussion Performance, Marshal.Copy and NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray

Discussion in 'General Discussion' started by huadongchuanmei, Oct 21, 2022.

  1. huadongchuanmei

    huadongchuanmei

    Joined:
    Jan 27, 2022
    Posts:
    6
    Hi,

    Our project shows remote webrtc video in unity Texture2D. The Video image data is captured from C++ native code.
    Currently, we copy the native image data to c# byte[] using Marshal.Copy, I think we should have a better way to avoid marshalling costs. (Remark: After I copy the data, native c++ will delete the data buffer, I can't control it)

    I hava two questions:
    1. Is NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray with Allocator.Persistent is better than Marshal.Copy to c# byte[]?

    2. Will the garbage collector free the NativeArray aotumaically? Will it call NativeArray.dispose()? Because another main thread will read the NativeArray to Texture2D, I can't free it in the backgound thread.

    Thanks!
     
  2. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    12,392
    You can allocate buffer at C# side and pass it into C++ so C++ size fills it.

    Basically, C#:
    Code (csharp):
    1.  
    2.     public static extern void processImage(
    3.         [In, Out] Color32[] src, int srcWidth, int srcHeight
    4.     );
    5.  
    C++:
    Code (csharp):
    1.  
    2. void processImage2(RGBA *src, int srcWidth, int srcHeight){
    3. .......
    4. }
    5.  
    However, you do need to raincheck if copying is performed behind the scenes anyway.

    In general interop between C# and C++ is not very pleasant, due to need to copy data often, plus you need plenty of glue code.