13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 25 Unsafe code}public static void Copy(void* src, void* dst, int count) {byte* ps = (byte*)src;byte* pd = (byte*)dst;if (ps > pd) {for (; count != 0; count--) *pd++ = *ps++;}else if (ps < pd) {for (ps += count, pd += count; count != 0; count--)*--pd = *--ps;}}// Frees a memory block.public static void Free(void* block) {if (!HeapFree(ph, 0, block)) throw new InvalidOperationException();}// Re-allocates a memory block. If the reallocation request is for a// larger size, the additional region of memory is automatically// initialized to zero.public static void* ReAlloc(void* block, int size) {void* result = HeapReAlloc(ph, HEAP_ZERO_MEMORY, block, size);if (result == null) throw new OutOfMemoryException();return result;}// Returns the size of a memory block.public static int SizeOf(void* block) {int result = HeapSize(ph, 0, block);if (result == -1) throw new InvalidOperationException();return result;}// Heap API flagsconst int HEAP_ZERO_MEMORY = 0x00000008;// Heap API functions[DllImport("kernel32")]static extern int GetProcessHeap();[DllImport("kernel32")]static extern void* HeapAlloc(int hHeap, int flags, int size);[DllImport("kernel32")]static extern bool HeapFree(int hHeap, int flags, void* block);[DllImport("kernel32")]static extern void* HeapReAlloc(int hHeap, int flags,void* block, int size);[DllImport("kernel32")]static extern int HeapSize(int hHeap, int flags, void* block);An example that uses the Memory class is given below:class Test{static void Main() {unsafe {byte* buffer = (byte*)Memory.Alloc(256);for (int i = 0; i < 256; i++) buffer[i] = (byte)i;byte[] array = new byte[256];fixed (byte* p = array) Memory.Copy(buffer, p, 256);Memory.Free(buffer);for (int i = 0; i < 256; i++) Console.WriteLine(array[i]);}}}333

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!