
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1074
|
Chapter 19: Unsafe Code
Solution
The FindInArray method, used in the following example, will return the position of
the element found in the array given a
fixed integer pointer. To see FindInFixedArray
in action, look at the TestFind method shown here:
public void TestFind( )
{
unsafe
{
int[] numericArr = new int[3] {2,4,6};
fixed(int* ptrArr = numericArr)
{
int foundPos = FindInFixedArray(ptrArr, numericArr.Length, 4);
if (foundPos > -1)
{
Console.WriteLine("Position in array: " + foundPos);
}
else
{
Console.WriteLine("Not Found");
}
}
}
}
The TestFind method creates an array of integers (numericArr), then uses the fixed
statement to create a pointer (ptrArr) and to make sure the array will not be moved
in memory by the garbage collector. The
ptrArr pointer variable is passed to the
FindInFixedArray method shown here to get the position of the element for the value
being searched for:
public unsafe int FindInFixedArray(int* theArray, int arrayLength,
int valueToFind)
{
for (int counter = 0; counter < arrayLength; counter++)
{
if (theArray[counter] == valueToFind)
{
return (counter);
}
}
// Return -1 if the value is not found in the array.
return (-1);
}
Notice that the FindInFixedArray method requires that the int* be fixed to be effec-
tive. If the pointer passed in to the
FindInFixedArray ...