Пример #1
0
        /// <summary>
        /// Allocates a block of memory at least as large as the amount requested.
        /// </summary>
        /// <param name="bytes">The number of bytes you want to allocate.</param>
        /// <returns>A pointer to a block of memory at least as large as <b>bytes</b>.</returns>
        /// <exception cref="OutOfMemoryException">Thrown if the memory manager could not fulfill the request for a memory block at least as large as <b>bytes</b>.</exception>
        public static IntPtr Allocate(ulong bytes)
        {
            if (hHeap == IntPtr.Zero)
            {
                throw new InvalidOperationException("heap has already been destroyed");
            }
            else
            {
                IntPtr block = SafeNativeMethods.HeapAlloc(hHeap, 0, new UIntPtr(bytes));

                if (block == IntPtr.Zero)
                {
                    throw new OutOfMemoryException("HeapAlloc returned a null pointer");
                }

                if (bytes > 0)
                {
                    GC.AddMemoryPressure((long)bytes);
                }

                return(block);
            }
        }
Пример #2
0
        /// <summary>
        /// Allocates a block of memory at least as large as the amount requested.
        /// </summary>
        /// <param name="bytes">The number of bytes you want to allocate.</param>
        /// <returns>A pointer to a block of memory at least as large as <b>bytes</b>.</returns>
        /// <exception cref="OutOfMemoryException">Thrown if the memory manager could not fulfill the request for a memory block at least as large as <b>bytes</b>.</exception>
        public static IntPtr Allocate(ulong bytes)
        {
            if (hHeap == IntPtr.Zero)
            {
                CreateHeap();
            }

            // Always initialize the memory to zero.
            // This ensures that the behavior of Allocate is the same as AllocateLarge.
            // AllocateLarge uses VirtualAlloc which is documented to initialize the allocated memory to zero.
            IntPtr block = SafeNativeMethods.HeapAlloc(hHeap, NativeConstants.HEAP_ZERO_MEMORY, new UIntPtr(bytes));

            if (block == IntPtr.Zero)
            {
                throw new OutOfMemoryException("HeapAlloc returned a null pointer");
            }

            if (bytes > 0)
            {
                MemoryPressureManager.AddMemoryPressure((long)bytes);
            }

            return(block);
        }