Example #1
0
        /// <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);
        }
Example #2
0
 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;
         }
     }
                ));
 }
Example #3
0
        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);
        }
Example #4
0
        /// <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);
        }
Example #5
0
        /// <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);
        }