/// <summary> /// Frees the unmanaged memory associated with an object. /// </summary> public static void Free(T obj) { IntPtr ptr = UnsafeTools.GetAddress(obj); IntPtr handle = ptr - 4; Marshal.FreeHGlobal(handle); }
public static TData FindInstance(ref T val, TData orig) { return(UnsafeTools.GetPointer( out val, ptr => { WeakReference <TData> wref; TData inst; if (Cache.TryGetValue(ptr, out wref) && wref.TryGetTarget(out inst)) { if (inst != orig) { inst = (TData)orig.Clone(); Cache[ptr] = new WeakReference <TData>(inst); } return inst; } else { inst = (TData)orig.Clone(); Cache[ptr] = new WeakReference <TData>(inst); return inst; } } )); }
static UnmanagedInstance() { var type = TypeOf <T> .TypeID; tptr = type.TypeHandle.Value; tsize = UnsafeTools.BaseInstanceSizeOf(type); init = new byte[tsize]; BitConverter.GetBytes((long)tptr).CopyTo(init, 4); }
/// <summary> /// Allocates unmanaged memory for an object. /// </summary> public static T Allocate() { IntPtr handle = Marshal.AllocHGlobal(tsize); Marshal.Copy(init, 0, handle, tsize); IntPtr ptr = handle + 4; return(UnsafeTools.GetObject(ptr) as T); }
/// <summary> /// Creates a new object handle in the unmanaged memory. /// </summary> /// <param name="t">The type of the object.</param> public ObjectHandle(Type t) { tptr = t.TypeHandle.Value; int size = UnsafeTools.BaseInstanceSizeOf(t); handle = Marshal.AllocHGlobal(size); byte[] zero = new byte[size]; Marshal.Copy(zero, 0, handle, size); IntPtr ptr = handle + 4; Marshal.WriteIntPtr(ptr, tptr); //write type ptr value = (T)UnsafeTools.GetObject(ptr); }