// This should comply and be a safe way to handle Memory. // This can actually be used in a class implementation such as: // public class MemoryBlock { // private Memory block; // public MemoryBlock(int size) { // block = new(new T[size], 0, size); // } // } // Thus all operations can be wrapped in the class for better memory management. // It would be better to just use a MemoryPool and create an owner for proper disposal instead of this hack. namespace MemoryTest { internal static class Program { private static Memory _memoryBuffer; private static void Alloc(int size) { byte[] bytes = new byte[size]; _memoryBuffer = new(bytes, 0, size); } private static bool Free() { if(!_memoryBuffer.IsEmpty) { byte[] nbuff = new byte[_memoryBuffer.Length]; Memory destroy = new(nbuff, 0, _memoryBuffer.Length); destroy.CopyTo(_memoryBuffer); _memoryBuffer = _memoryBuffer.Trim(0); } Console.WriteLine("Memory Freed"); return true; } private static byte GetMemoryByte(int location) { return _memoryBuffer.Span[location]; } private static void SetMemory(byte[] buffer) { var tmp = new Memory(buffer); if(!tmp.TryCopyTo(_memoryBuffer)) { Console.WriteLine("Could not place memory"); } } private static void PrintMemory() { for (int i = 0; i < _memoryBuffer.Length; i++) { var b = GetMemoryByte(i); Console.Write((char)b); } Console.WriteLine(); } private static void Main(string[] args) { string msg = "This is a test."; Alloc(msg.Length); SetMemory(System.Text.Encoding.ASCII.GetBytes(msg)); PrintMemory(); Free(); PrintMemory(); msg = "Oh look, another test"; Alloc(msg.Length); SetMemory(System.Text.Encoding.ASCII.GetBytes(msg)); PrintMemory(); Free(); PrintMemory(); } } }