using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace XCS2NS { public class SafeMemoryManipulator : IDisposable { private IntPtr buffer; private int bufferSize; private bool disposed = false; public SafeMemoryManipulator(int size) { bufferSize = size; buffer = Marshal.AllocHGlobal(bufferSize); Console.WriteLine("Buffer allocated with size " + bufferSize); } public void WriteToBuffer(int value, int index) { if (index < 0 || index * sizeof(int) >= bufferSize) { throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range."); } unsafe { int* ptr = (int*)buffer.ToPointer(); ptr[index] = value; Console.WriteLine($"Value {value} written at buffer index {index}."); } } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // Optionally dispose managed state (managed objects). } if (buffer != IntPtr.Zero) { Marshal.FreeHGlobal(buffer); Console.WriteLine("Buffer freed."); buffer = IntPtr.Zero; } disposed = true; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~SafeMemoryManipulator() { Dispose(false); } } }