コード例 #1
0
 public void Free()
 {
     if (_ptr != null)
     {
         NativeMemory.Free(_ptr);
     }
 }
コード例 #2
0
        public void Dispose()
        {
            if (!_isDisposed.Raise())
            {
                return;
            }

            lock (this)
            {
                if (_olderBuffers != null)
                {
                    foreach (var unusedBuffer in _olderBuffers)
                    {
                        NativeMemory.Free((byte *)unusedBuffer.Item1, unusedBuffer.Item2, unusedBuffer.Item3);
                    }
                    _olderBuffers = null;
                }
                if (_ptrStart != null)
                {
                    NativeMemory.Free(_ptrStart, _allocated, _allocatingThread);
                    _ptrStart = null;
                }

                GC.SuppressFinalize(this);
            }
        }
コード例 #3
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;

            GC.SuppressFinalize(this);
            _options.IoMetrics.FileClosed(_filename);
            _readHandle?.Dispose();
            _readHandle = null;
            _handle?.Dispose();
            _handle = null;
            if (_nativeOverlapped != null)
            {
                NativeMemory.Free((byte *)_nativeOverlapped, sizeof(NativeOverlapped));
                _nativeOverlapped = null;
            }

            if (DeleteOnClose)
            {
                try
                {
                    File.Delete(_filename);
                }
                catch (Exception)
                {
                    // if we can't delete, nothing that we can do here.
                }
            }
        }
コード例 #4
0
ファイル: NativeMemoryTests.cs プロジェクト: z77ma/runtime
        public void AllocZeroedZeroElementSizeTest()
        {
            void *ptr = NativeMemory.AllocZeroed(1, 0);

            Assert.True(ptr != null);
            NativeMemory.Free(ptr);
        }
コード例 #5
0
ファイル: NativeMemoryTests.cs プロジェクト: z77ma/runtime
        public void AllocZeroedZeroElementCountTest()
        {
            void *ptr = NativeMemory.AllocZeroed(0, 1);

            Assert.True(ptr != null);
            NativeMemory.Free(ptr);
        }
コード例 #6
0
    private void FreeNativeMemory()
    {
        QUIC_BUFFER *buffers = _buffers;

        _buffers = null;
        NativeMemory.Free(buffers);
    }
コード例 #7
0
        private unsafe FileVersionInfo(string fileName)
        {
            _fileName = fileName;

            uint infoSize = Interop.Version.GetFileVersionInfoSizeEx(Interop.Version.FileVersionInfoType.FILE_VER_GET_LOCALISED, _fileName, out _);

            if (infoSize != 0)
            {
                void *memPtr = NativeMemory.Alloc(infoSize);
                try
                {
                    if (Interop.Version.GetFileVersionInfoEx(
                            Interop.Version.FileVersionInfoType.FILE_VER_GET_LOCALISED | Interop.Version.FileVersionInfoType.FILE_VER_GET_NEUTRAL,
                            _fileName,
                            0U,
                            infoSize,
                            memPtr))
                    {
                        // Some dlls might not contain correct codepage information, in which case the lookup will fail. Explorer will take
                        // a few shots in dark. We'll simulate similar behavior by falling back to the following lang-codepages.
                        uint lcp = GetLanguageAndCodePage(memPtr);
                        _ = GetVersionInfoForCodePage(memPtr, lcp.ToString("X8")) ||
                            (lcp != 0x040904B0 && GetVersionInfoForCodePage(memPtr, "040904B0")) || // US English + CP_UNICODE
                            (lcp != 0x040904E4 && GetVersionInfoForCodePage(memPtr, "040904E4")) || // US English + CP_USASCII
                            (lcp != 0x04090000 && GetVersionInfoForCodePage(memPtr, "04090000"));   // US English + unknown codepage
                    }
                }
                finally
                {
                    NativeMemory.Free(memPtr);
                }
            }
        }
コード例 #8
0
    /**
     * Releases all physics objects, including memory blocks containing deserialized data
     */
    public static void cleanupPhysics()
    {
        PX_RELEASE(ref gScene);
        PX_RELEASE(ref gDispatcher);
        PxCloseExtensions();

        PX_RELEASE(ref gPhysics); // releases all objects
        PX_RELEASE(ref gCooking);
        if (gPvd != null)
        {
            PxPvdTransport *transport = gPvd->getTransport();
            gPvd->release();
            gPvd = null;
            PX_RELEASE(ref transport);
        }

        // Now that the objects have been released, it's safe to release the space they occupy
        for (uint i = 0; i < gMemBlockCount; i++)
        {
            NativeMemory.Free(gMemBlocks[i]);
        }

        gMemBlockCount = 0;

        PX_RELEASE(ref gFoundation);
    }
コード例 #9
0
 /// <summary>
 /// Frees any allocated unmanaged memory.
 /// </summary>
 public void Free()
 {
     if (_allocated)
     {
         NativeMemory.Free(_unmanagedValue);
     }
 }
コード例 #10
0
        public unsafe void LZ4Test(int size)
        {
            byte *encodeInput = NativeMemory.AllocateMemory(size);
            int   compressedSize;
            byte *encodeOutput;

            var originStr           = string.Join("", Enumerable.Repeat(1, size).Select(x => "sample"));
            var bytes               = Encoding.UTF8.GetBytes(originStr);
            var maximumOutputLength = LZ4.MaximumOutputLength(bytes.Length);

            fixed(byte *pb = bytes)
            {
                encodeOutput   = NativeMemory.AllocateMemory((int)maximumOutputLength);
                compressedSize = LZ4.Encode64(pb, encodeOutput, bytes.Length, (int)maximumOutputLength);
            }

            Array.Clear(bytes, 0, bytes.Length);
            fixed(byte *pb = bytes)
            {
                LZ4.Decode64(encodeOutput, compressedSize, pb, bytes.Length, true);
            }

            var actual = Encoding.UTF8.GetString(bytes);

            Assert.Equal(originStr, actual);

            NativeMemory.Free(encodeInput, size);
            NativeMemory.Free(encodeOutput, maximumOutputLength);
        }
コード例 #11
0
ファイル: NativeMemoryTests.cs プロジェクト: z77ma/runtime
        public void AllocZeroByteCountTest()
        {
            void *ptr = NativeMemory.Alloc(0);

            Assert.True(ptr != null);
            NativeMemory.Free(ptr);
        }
コード例 #12
0
ファイル: NativeMemoryTests.cs プロジェクト: z77ma/runtime
        public void ReallocNullPtrZeroSizeTest()
        {
            void *ptr = NativeMemory.Realloc(null, 0);

            Assert.True(ptr != null);
            NativeMemory.Free(ptr);
        }
コード例 #13
0
        public void ResetArena()
        {
            // Reset current arena buffer
            _ptrCurrent = _ptrStart;
            Array.Clear(_freed, 0, _freed.Length);

            if (_olderBuffers == null)
            {
                // there were no new allocations in this round
                if (_allocated / 2 > _used && _allocated > _initialSize * 2)
                {
                    // we used less than half the memory we have, so let us reduce it

                    if (_ptrStart != null)
                    {
                        NativeMemory.Free(_ptrStart, _allocated, _allocatingThread);
                    }

                    _allocated  = Math.Max(_allocated / 2, _initialSize);
                    _ptrCurrent = _ptrStart = null;
                }
                _used     = 0;
                TotalUsed = 0;
                return;
            }
            // Free old buffers not being used anymore
            foreach (var unusedBuffer in _olderBuffers)
            {
                _used += unusedBuffer.Item2;
                NativeMemory.Free((byte *)unusedBuffer.Item1, unusedBuffer.Item2, unusedBuffer.Item3);
            }
            _olderBuffers = null;
            if (_used <= _allocated)
            {
                _used     = 0;
                TotalUsed = 0;
                return;
            }
            // we'll likely need more memory in the next round, let us increase the size we hold on to

            if (_ptrStart != null)
            {
                NativeMemory.Free(_ptrStart, _allocated, _allocatingThread);
            }

            // we'll allocate some multiple of the currently allocated amount, that will prevent big spikes in memory
            // consumption and has the worst case usage of doubling memory utilization

            var newSize = (_used / _allocated + (_used % _allocated == 0 ? 0 : 1)) * _allocated;

            _allocated = newSize;
            _used      = 0;
            TotalUsed  = 0;
            if (_allocated > MaxArenaSize)
            {
                _allocated = MaxArenaSize;
            }
            _ptrCurrent = _ptrStart = null;
        }
コード例 #14
0
        public static uint Release(IDXGIFactory4As6Backcompat * @this)
        {
            @this->dxgiFactory4->Release();

            NativeMemory.Free(@this);

            return(0);
        }
コード例 #15
0
            public static void Free(void *block)
            {
#if NET6_0_OR_GREATER
                NativeMemory.Free(block);
#else
                Marshal.FreeHGlobal((System.IntPtr)block);
#endif
            }
コード例 #16
0
 public void Dispose()
 {
     Disposed = true;
     foreach (var buffer in _buffers)
     {
         NativeMemory.Free(buffer.Pointer, buffer.SizeInPages * _options.PageSize);
     }
     _buffers = ImmutableAppendOnlyList <Buffer> .Empty;
 }
コード例 #17
0
ファイル: Image.cs プロジェクト: Golle/Titan
 public unsafe void Dispose()
 {
     if (_buffer != null)
     {
         NativeMemory.Free(_buffer);
         _buffer    = null;
         _imageSize = 0;
     }
 }
コード例 #18
0
ファイル: NativeMemoryTests.cs プロジェクト: z77ma/runtime
        public void AllocZeroedElementCountTest()
        {
            void *ptr = NativeMemory.AllocZeroed(1, 1);

            Assert.True(ptr != null);
            Assert.Equal(expected: 0, actual: ((byte *)ptr)[0]);

            NativeMemory.Free(ptr);
        }
コード例 #19
0
 public void TestNativeAlloc()
 {
     for (var i = 0; i < IterCount; i++)
     {
         var p = (byte *)NativeMemory.Alloc((nuint)Size);
         Consume(&p);
         NativeMemory.Free(p);
     }
 }
コード例 #20
0
        private static unsafe void CleanupScatterGatherBuffers(MemoryHandle[] handlesToDispose, IntPtr segmentsPtr)
        {
            foreach (MemoryHandle handle in handlesToDispose)
            {
                handle.Dispose();
            }

            NativeMemory.Free((void *)segmentsPtr);
        }
コード例 #21
0
ファイル: NativeList.cs プロジェクト: zentia/EventSource
    private void Resize()
    {
        int   newCapacity = data->capacity * 2;
        byte *newArr      = NativeMemory.Alloc(data->structSize * newCapacity, NativeMemory.NativeMemoryType.RawList);

        NativeMemory.Copy(newArr, data->arrayPtr, data->structSize * data->capacity);
        NativeMemory.Free(data->arrayPtr);
        data->arrayPtr = newArr;
        data->capacity = newCapacity;
    }
コード例 #22
0
        public bool Read(byte *buffer, long numOfBytes, long offsetInFile)
        {
            if (_readHandle == null)
            {
                var handle = Win32NativeFileMethods.CreateFile(_filename.FullPath,
                                                               Win32NativeFileAccess.GenericRead,
                                                               Win32NativeFileShare.Write | Win32NativeFileShare.Read | Win32NativeFileShare.Delete,
                                                               IntPtr.Zero,
                                                               Win32NativeFileCreationDisposition.OpenExisting,
                                                               Win32NativeFileAttributes.Normal,
                                                               IntPtr.Zero);
                if (handle.IsInvalid)
                {
                    throw new IOException("When opening file " + _filename, new Win32Exception(Marshal.GetLastWin32Error()));
                }

                _readHandle = handle;
            }

            var nativeOverlapped = (NativeOverlapped *)NativeMemory.AllocateMemory(sizeof(NativeOverlapped));

            try
            {
                nativeOverlapped->OffsetLow   = (int)(offsetInFile & 0xffffffff);
                nativeOverlapped->OffsetHigh  = (int)(offsetInFile >> 32);
                nativeOverlapped->EventHandle = IntPtr.Zero;
                while (numOfBytes > 0)
                {
                    if (Win32NativeFileMethods.ReadFile(_readHandle, buffer, (int)Math.Min(numOfBytes, int.MaxValue), out int read, nativeOverlapped) == false)
                    {
                        int lastWin32Error = Marshal.GetLastWin32Error();
                        if (lastWin32Error == Win32NativeFileMethods.ErrorHandleEof)
                        {
                            return(false);
                        }
                        if (lastWin32Error == Win32NativeFileMethods.ErrorInvalidHandle)
                        {
                            _readHandle = null;
                        }
                        throw new Win32Exception(lastWin32Error, $"Unable to read from {_filename}, error code: {lastWin32Error}");
                    }

                    numOfBytes   -= read;
                    buffer       += read;
                    offsetInFile += read;
                    nativeOverlapped->OffsetLow  = (int)(offsetInFile & 0xffffffff);
                    nativeOverlapped->OffsetHigh = (int)(offsetInFile >> 32);
                }
                return(true);
            }
            finally
            {
                NativeMemory.Free((byte *)nativeOverlapped, sizeof(NativeOverlapped));
            }
        }
コード例 #23
0
ファイル: NativeMemoryTests.cs プロジェクト: z77ma/runtime
        public void ReallocZeroSizeTest()
        {
            void *ptr = NativeMemory.Alloc(1);

            Assert.True(ptr != null);

            void *newPtr = NativeMemory.Realloc(ptr, 0);

            Assert.True(newPtr != null);
            NativeMemory.Free(newPtr);
        }
コード例 #24
0
 public void Dispose()
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         const int MEM_RELEASE = 0x8000;
         VirtualFree(_addr, 0, MEM_RELEASE);
     }
     else
     {
         NativeMemory.Free(_addr);
     }
 }
コード例 #25
0
        void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (_ptrB != default)
                {
                    NativeMemory.Free(_ptrB);
                    _ptrB = default;
                }

                _disposed = true;
            }
        }
コード例 #26
0
        private static unsafe void FreeArray(byte **arr, int length)
        {
            if (arr != null)
            {
                // Free each element of the array
                for (int i = 0; i < length; i++)
                {
                    NativeMemory.Free(arr[i]);
                }

                // And then the array itself
                NativeMemory.Free(arr);
            }
        }
コード例 #27
0
        public void CopyTest(int sourceSize, int destinationSize, int byteCount)
        {
            void *source      = NativeMemory.AllocZeroed((nuint)sourceSize);
            void *destination = NativeMemory.AllocZeroed((nuint)destinationSize);

            new Span <byte>(source, sourceSize).Fill(0b10101010);

            NativeMemory.Copy(source, destination, (nuint)byteCount);

            Equals(byteCount - 1, new Span <byte>(destination, destinationSize).LastIndexOf <byte>(0b10101010));

            NativeMemory.Free(source);
            NativeMemory.Free(destination);
        }
コード例 #28
0
 /// <summary>
 /// Release the native memory of individual buffers and allows reuse of this struct.
 /// </summary>
 public void Reset()
 {
     for (int i = 0; i < _count; ++i)
     {
         if (_buffers[i].Buffer is null)
         {
             break;
         }
         byte *buffer = _buffers[i].Buffer;
         _buffers[i].Buffer = null;
         NativeMemory.Free(buffer);
         _buffers[i].Length = 0;
     }
 }
コード例 #29
0
        /// <summary>
        /// Gets the process information for a given process
        /// </summary>
        /// <param name="pid">The PID (process ID) of the process</param>
        /// <returns>
        /// Returns a valid ProcessInfo struct for valid processes that the caller
        /// has permission to access; otherwise, returns null
        /// </returns>
        public static unsafe ProcessInfo GetProcessInfoById(int pid)
        {
            // Negative PIDs are invalid
            if (pid < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pid));
            }

            ProcessInfo info;

            kinfo_proc *kinfo = GetProcInfo(pid, true, out int count);

            try
            {
                if (count < 1)
                {
                    throw new ArgumentOutOfRangeException(nameof(pid));
                }

                var process = new ReadOnlySpan <kinfo_proc>(kinfo, count);

                // Get the process information for the specified pid
                info = new ProcessInfo();

                info.ProcessName  = Marshal.PtrToStringAnsi((IntPtr)kinfo->ki_comm) !;
                info.BasePriority = kinfo->ki_nice;
                info.VirtualBytes = (long)kinfo->ki_size;
                info.WorkingSet   = kinfo->ki_rssize;
                info.SessionId    = kinfo->ki_sid;

                for (int i = 0; i < process.Length; i++)
                {
                    var ti = new ThreadInfo()
                    {
                        _processId    = pid,
                        _threadId     = (ulong)process[i].ki_tid,
                        _basePriority = process[i].ki_nice,
                        _startAddress = (IntPtr)process[i].ki_tdaddr
                    };
                    info._threadInfoList.Add(ti);
                }
            }
            finally
            {
                NativeMemory.Free(kinfo);
            }

            return(info);
        }
コード例 #30
0
ファイル: MessageBufferHG.cs プロジェクト: FelCore/FelCore
        void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
            }

            NativeMemory.Free(_storage);

            _disposed = true;
        }