Search Unity

Pinning C# Arrays (GCHandle vs. PinGCObjectAndGetAddress)

Discussion in 'Entity Component System' started by fholm, Nov 19, 2018.

  1. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    Was fiddling with this over the weekend, but couldn't figure it out... so here goes:

    So I need to pin some C# arrays and get the address of the first element (Byte[] arrays to be specific). I'm used to doing this with GCHandle.Alloc(array, GCHandleType.Pinned) but I saw that there's a method called PinGCObjectAndGetAddress in the Unity.Collections.LowLevel.Unsafe.UnsafeUtility class.

    1) What is the difference between doing it the regular .NET way with GCHandle and PinGCObjectAndGetAddress?

    2) Can I use PinGCObjectAndGetAddress to pin arrays, and if thats the case where does the address that is returned point to? The first element?

    I thought I saw a method specifically designed to pin GC arrays somewhere in the low level APIs exposed ... but couldn't find it again.
     
    Last edited: Nov 19, 2018
    xman7c7 likes this.
  2. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    Okey so I installed the latest 2018.3 beta10, and with this version it seems a method called PinGCArrayAndGetDataAddress is available in the UnityEngine.CoreModule.dll on the Unity.Collections.LowLevel.Unsafe.UnsafeUtility class.

    Can someone from Unity (as I assume nobody else knows how these functions really work) confirm something:

    1) Is the void pointer returned from the method the pointer to the first element?
    2) The handle returned as a ulong on the second parameter, that can be passed into ReleaseGCObject ? There is no ReleaseGCArray so I assume this is where you're supposed to release a pinned array also?
     
  3. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    Anyone that knows this? :)
     
  4. capyvara

    capyvara

    Joined:
    Mar 11, 2010
    Posts:
    80
    AFAIK:

    1) Yes
    2) Yes
     
  5. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    From my tests I've seen this to be the correct answers to both questions, but it'd still be nice to have an official word from a Unity employee.
     
  6. capyvara

    capyvara

    Joined:
    Mar 11, 2010
    Posts:
    80
  7. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052