13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATION[Example: In the exampleusing System;class Test{static string IntToString(int value) {int n = value >= 0 ? value : -value;unsafe {char* buffer = stackalloc char[16];char* p = buffer + 16;do {*--p = (char)(n % 10 + '0');n /= 10;} while (n != 0);if (value < 0) *--p = '-';return new string(p, 0, (int)(buffer + 16 - p));}}static void Main() {Console.WriteLine(IntToString(12345));Console.WriteLine(IntToString(-999));}}a stackalloc initializer is used in the IntToString method to allocate a buffer of 16 characters on thestack. The buffer is automatically discarded when the method returns. end example]25.8 Dynamic memory allocationExcept for the stackalloc operator, <strong>C#</strong> provides no predefined constructs for managing non-garbagecollected memory. Such services are typically provided by supporting class libraries or imported directlyfrom the underlying operating system. [Example: For example, the Memory class below illustrates how theheap functions of an underlying operating system might be accessed from <strong>C#</strong>:using System;using System.Runtime.InteropServices;public unsafe class Memory{// Handle for the process heap. This handle is used in all calls to// the HeapXXX APIs in the methods below.static int ph = GetProcessHeap();// Private instance constructor to prevent instantiation.private Memory() {}// Allocates a memory block of the given size. The allocated memory is// automatically initialized to zero.public static void* Alloc(int size) {void* result = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);if (result == null) throw new OutOfMemoryException();return result;}// Copies count bytes from src to dst. The source and destination// blocks are permitted to overlap.332

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

Saved successfully!

Ooh no, something went wrong!