Esempio n. 1
0
        public MemoryChunkBuilder ReserveAligned(ulong length)
        {
            var necessaryOffset = MemoryAlignmentHelper.RequiredOffset(0, AllocationSize, length);

            AllocationSize += length + necessaryOffset;
            return(this);
        }
Esempio n. 2
0
        /// <summary>
        /// Reserves part of the memory region for an array of the specififed type and length.
        /// The part reserved will be aligned on a <see cref="PageAlignmentBytes"/> byte boundary.
        /// </summary>
        /// <typeparam name="T">The type of the array elements.</typeparam>
        /// <param name="length">The count of items in the array.</param>
        /// <returns>A pointer to the first item in the array.</returns>
        public unsafe T *GetArrayAligned <T>(ulong length)
            where T : unmanaged
        {
            var lengthInBytes   = (ulong)Unsafe.SizeOf <T>() * length;
            var necessaryOffset = MemoryAlignmentHelper.RequiredOffset((ulong)_ptr, _offset, length);

            Debug.Assert(_offset + lengthInBytes + necessaryOffset <= _bytesReserved);

            var result = (T *)((byte *)_ptr + _offset + necessaryOffset);

            _offset += lengthInBytes + necessaryOffset;

            return(result);
        }
Esempio n. 3
0
        public LargePageMemoryChunk(ulong length)
        {
            const MemoryAllocationType flags = MemoryAllocationType.MemReserve | MemoryAllocationType.MemCommit;
            const string lockMemory          = "SeLockMemoryPrivilege";

            _bytesReserved = MemoryAlignmentHelper.LargePageMultiple(length);
            try
            {
                using var privs = PrivilegeHolder.EnablePrivilege(lockMemory);
                if (privs != null)
                {
                    const MemoryAllocationType largeFlag = flags | MemoryAllocationType.MemLargePages;
                    _ptr = NativeMethods.VirtualAlloc(IntPtr.Zero, (IntPtr)_bytesReserved, largeFlag, MemoryProtectionConstants.PageReadwrite);
                    GC.KeepAlive(privs);
                }
            }
            catch (ObjectDisposedException)
            {
                // TODO: fix the underlying cause
            }

            _ptr = NativeMethods.VirtualAlloc(IntPtr.Zero, (IntPtr)_bytesReserved, flags, MemoryProtectionConstants.PageReadwrite);
        }