Search Unity

  1. Unity 2020 LTS & Unity 2021.1 have been released.
    Dismiss Notice

Is there any way to get native pointers to Unity's C++ objects?

Discussion in 'Data Oriented Technology Stack' started by TFlippy, May 4, 2020.

  1. TFlippy

    TFlippy

    Joined:
    Nov 12, 2014
    Posts:
    27
    I'm rewriting parts of my project to be able to utilize the DOTS framework (e.g. storing object data as ECS components, changing how objects are defined and processed), but as the DOTS framework is still quite feature-incomplete, I have to use GameObjects and other managed objects (Rigidbody2D, AudioSource, SpriteRenderer components).

    So i'm asking - is there any way to get a native pointer / unmanaged reference to GameObjects and Components? I'm currently using a weak-referenced GCHandle, but it feels somewhat cumbersome.
     
  2. tarahugger

    tarahugger

    Joined:
    Jul 18, 2014
    Posts:
    129
    Use it at your own risk. You'll have to map the native structures yourself and there are no guarantees the data won't move. it's generally going to be a bad idea

    Code (CSharp):
    1. public static unsafe class UnityObjectExtensions
    2. {
    3.     private static MethodInfo _methodInfo;
    4.  
    5.     static UnityObjectExtensions()
    6.     {
    7.         _methodInfo = typeof(UnityEngine.Object).GetMethod("GetCachedPtr", BindingFlags.Instance | BindingFlags.NonPublic);
    8.     }
    9.  
    10.     public static TDelegate CreateDelegate<TDelegate>(UnityEngine.Object unityObject) where TDelegate : Delegate
    11.     {
    12.         return (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), unityObject, _methodInfo);
    13.     }
    14.  
    15.     public static ref T GetUnsafeRef<T>(this UnityEngine.Object unityObject) where T : struct
    16.     {
    17.         return ref UnsafeUtilityEx.AsRef<T>((void*)CreateDelegate<Func<IntPtr>>(unityObject).Invoke());
    18.     }
    19.  
    20.     public static T* GetUnsafePtr<T>(this UnityEngine.Object unityObject) where T : unmanaged
    21.     {
    22.         return (T*)CreateDelegate<Func<IntPtr>>(unityObject).Invoke();
    23.     }
    24. }
     
  3. eizenhorn

    eizenhorn

    Joined:
    Oct 17, 2016
    Posts:
    2,221
    Use companions workflow instead?
     
unityunity