Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Nbsp;   Unsafe Array Access and Fixed-Size Array

Unsafe array access is very powerful because it allows you to access:

 

■ Elements within a managed array object that resides on the heap (as the previous section demonstrated).

■ Elements within an array that resides on an unmanaged heap. The SecureString example in Chapter 14, “Chars, Strings, and Working with Text,” demonstrated using unsafe array access on an array returned from calling the System.Runtime.InteropServices.Marshal class’s SecureStringToCoTaskMemUnicode method.

■ Elements within an array that resides on the thread’s stack.

 

In cases in which performance is extremely critical, you could avoid allocating a managed array object on the heap and instead allocate the array on the thread’s stack by using C#’s stackalloc statement (which works a lot like C’s alloca function). The stackalloc statement can be used to create a single-dimensional, zero-based array of value type elements only, and the value type must not contain any reference type fields. Really, you should think of this as allocating a block of memory that you can manipulate by using unsafe pointers, and therefore, you cannot pass the address of this memory buffer to the vast majority of FCL methods. Of course, the stack-allocated memory (array) will automatically be freed when the method returns; this is where we get the performance improve- ment. Using this feature also requires you to specify the /unsafe switch to the C# compiler.


The StackallocDemo method in the following code shows an example of how to use C#’s

stackalloc statement.

 

using System;

 

public static class Program { public static void Main() {

StackallocDemo(); InlineArrayDemo();

}

 

private static void StackallocDemo() { unsafe {

const Int32 width = 20;

Char* pc = stackalloc Char[width]; // Allocates array on stack String s = "Jeffrey Richter"; // 15 characters

for (Int32 index = 0; index < width; index++) { pc[width ­ index ­ 1] =

(index < s.Length) ? s[index] : '.';

}

 

// The following line displays ".....rethciR yerffeJ" Console.WriteLine(new String(pc, 0, width));

}

}

 

private static void InlineArrayDemo() { unsafe {

CharArray ca; // Allocates array on stack Int32 widthInBytes = sizeof(CharArray);

Int32 width = widthInBytes / 2;

String s = "Jeffrey Richter"; // 15 characters for (Int32 index = 0; index < width; index++) {

ca.Characters[width ­ index ­ 1] = (index < s.Length) ? s[index] : '.';

}

 

// The following line displays ".....rethciR yerffeJ" Console.WriteLine(new String(ca.Characters, 0, width));

}

}

}

 

internal unsafe struct CharArray {

// This array is embedded inline inside the structure public fixed Char Characters[20];

}


Normally, because arrays are reference types, an array field defined in a structure is really just a pointer or reference to an array; the array itself lives outside of the structure’s memory. However, it is possible to embed an array directly inside a structure as shown by the CharArray structure in the preceding code. To embed an array directly inside a structure, there are several requirements:



■ The type must be a structure (value type); you cannot embed an array inside a class (reference type).

■ The field or its defining structure must be marked with the unsafe keyword.

 

■ The array field must be marked with the fixed keyword.

 

■ The array must be single-dimensional and zero-based.

 

■ The array’s element type must be one of the following types: Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, or Double.

Inline arrays are typically used for scenarios that involve interoperating with unmanaged code where the unmanaged data structure also has an inline array. However, inline arrays can be used in other scenarios as well. The InlineArrayDemo method in the code shown earlier offers an example of how to use an inline array. The InlineArrayDemo method performs the same function as the StackallocDemo method; it just does it in a different way.


C HA P T E R 1 7

Delegates

In this chapter:

A First Look at Delegates......................................................................... 391

Using Delegates to Call Back Static Methods............................................ 394

Using Delegates to Call Back Instance Methods........................................ 395

Demystifying Delegates........................................................................... 396

Using Delegates to Call Back Many Methods (Chaining)........................... 400


Date: 2016-03-03; view: 692


<== previous page | next page ==>
Nbsp;   Array Internals | Nbsp;   A First Look at Delegates
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.007 sec.)