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.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

NativeArray to IntPtr

Discussion in 'Entity Component System' started by MikeGameDev, Sep 19, 2018.

  1. MikeGameDev

    MikeGameDev

    Joined:
    Dec 28, 2012
    Posts:
    19
    I am obtaining a NativeArray using AsyncGPUReadbackRequest and would like to pass the data into a plugin expecting an IntPtr as input.

    Is there a fast way to obtain a IntPtr from a NativeArray? Currently I am converting the NativeArray into a managed array which is very slow.

    EDIT: Additional details, this is what I'm currently doing:

    Code (CSharp):
    1. byte[] textureData = asyncGpuMemoryReadRequest.GetData<byte>().ToArray();
    2.  
    3. unityScreenTexturePtr = Marshal.AllocHGlobal(textureData.Length);
    4.  
    5. Marshal.Copy(textureData, 0, unityScreenTexturePtr, textureData.Length);
    6.  
    7.  
     
    Last edited: Sep 19, 2018
  2. pcysl5edgo

    pcysl5edgo

    Joined:
    Jun 3, 2018
    Posts:
    65
    Sample Code;
    Code (CSharp):
    1. using(var array = new NativeArray<byte>(114514, Allocator.TempJob))
    2. {
    3.     unsafe{
    4.         var ptr = (IntPtr)Unity.Collections.LowLevel.Unsafe.UnsafeArrayUtility.GetUnsafePtr(array); // void* -> IntPtr explicit conversion.
    5.         hoge_API_CALL(ptr);
    6.     }
    7. }
     
  3. MikeGameDev

    MikeGameDev

    Joined:
    Dec 28, 2012
    Posts:
    19
    Thanks that works perfectly.
     
    pcysl5edgo likes this.
  4. Deleted User

    Deleted User

    Guest

    Hello. Is there any method to convert it back? IntPtr to NativeArray<byte>?

    Thank you.
     
  5. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,624
    NativeArray<T> NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(void* dataPointer, int length, Allocator allocator)