Get Memory Address of .NET Object (C#)

后端 未结 5 1998
醉酒成梦
醉酒成梦 2021-01-02 03:05

I am trying to track down a bug in the mono runtime where a variable appears to be allocated to one valid object, and then is reassigned later to a bogus object, specificall

5条回答
  •  清酒与你
    2021-01-02 03:35

    My alternatives... Also @ This similar question

    #region AddressOf
    
        /// 
        /// Provides the current address of the given object.
        /// 
        /// 
        /// 
        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        public static System.IntPtr AddressOf(object obj)
        {
            if (obj == null) return System.IntPtr.Zero;
    
            System.TypedReference reference = __makeref(obj);
    
            System.TypedReference* pRef = &reference;
    
            return (System.IntPtr)pRef; //(&pRef)
        }
    
        /// 
        /// Provides the current address of the given element
        /// 
        /// 
        /// 
        /// 
        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        public static System.IntPtr AddressOf(T t)
            //refember ReferenceTypes are references to the CLRHeader
            //where TOriginal : struct
        {
            System.TypedReference reference = __makeref(t);
    
            return *(System.IntPtr*)(&reference);
        }
    
        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        static System.IntPtr AddressOfRef(ref T t)
        //refember ReferenceTypes are references to the CLRHeader
        //where TOriginal : struct
        {
            System.TypedReference reference = __makeref(t);
    
            System.TypedReference* pRef = &reference;
    
            return (System.IntPtr)pRef; //(&pRef)
        }
    
        /// 
        /// Returns the unmanaged address of the given array.
        /// 
        /// 
        ///  if null, otherwise the address of the array
        [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
        public static System.IntPtr AddressOfByteArray(byte[] array)
        {
            if (array == null) return System.IntPtr.Zero;
    
            fixed (byte* ptr = array)
                return (System.IntPtr)(ptr - 2 * sizeof(void*)); //Todo staticaly determine size of void?
        }
    
        #endregion
    

提交回复
热议问题