2 using System.Diagnostics;
3 using System.Runtime.InteropServices;
8 /// ガベージコレクション対象外のメモリの確保と解放。
9 /// (引用元: https://msdn.microsoft.com/ja-jp/library/aa664786(v=vs.71).aspx )
11 public unsafe class Memory
13 // Handle for the process heap. This handle is used in all calls to the
14 // HeapXXX APIs in the methods below.
15 static int ph = GetProcessHeap();
17 // Private instance constructor to prevent instantiation.
22 // Allocates a memory block of the given size. The allocated memory is
23 // automatically initialized to zero.
24 public static void* Alloc( int size )
26 void* result = HeapAlloc( ph, HEAP_ZERO_MEMORY, size );
27 if( result == null ) throw new OutOfMemoryException();
29 IntPtr pr = new IntPtr( result );
30 //Debug.WriteLine( $"HeapAlloc, {size}bytes, address={pr.ToString()}" );
35 // Copies count bytes from src to dst. The source and destination
36 // blocks are permitted to overlap.
37 public static void Copy( void* src, void* dst, int count )
39 byte* ps = (byte*) src;
40 byte* pd = (byte*) dst;
43 for( ; count != 0; count-- ) *pd++ = *ps++;
47 for( ps += count, pd += count; count != 0; count-- ) *--pd = *--ps;
52 public static void Zero( void* dst, int count )
54 byte* pd = (byte*) dst;
55 for( ; count != 0; count-- ) *pd++ = 0;
58 // Frees a memory block.
59 public static void Free( void* block )
61 IntPtr pr = new IntPtr( block );
62 //Debug.WriteLine( $"HeapFree, address={pr.ToString()}" );
64 if( !HeapFree( ph, 0, block ) ) throw new InvalidOperationException();
67 // Re-allocates a memory block. If the reallocation request is for a
68 // larger size, the additional region of memory is automatically
69 // initialized to zero.
70 public static void* ReAlloc( void* block, int size )
72 void* result = HeapReAlloc( ph, HEAP_ZERO_MEMORY, block, size );
73 if( result == null ) throw new OutOfMemoryException();
77 // Returns the size of a memory block.
78 public static int SizeOf( void* block )
80 int result = HeapSize( ph, 0, block );
81 if( result == -1 ) throw new InvalidOperationException();
86 const int HEAP_ZERO_MEMORY = 0x00000008;
89 [DllImport( "kernel32" )]
90 static extern int GetProcessHeap();
92 [DllImport( "kernel32" )]
93 static extern void* HeapAlloc( int hHeap, int flags, int size );
95 [DllImport( "kernel32" )]
96 static extern bool HeapFree( int hHeap, int flags, void* block );
98 [DllImport( "kernel32" )]
99 static extern void* HeapReAlloc( int hHeap, int flags, void* block, int size );
101 [DllImport( "kernel32" )]
102 static extern int HeapSize( int hHeap, int flags, void* block );