
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Switching Unknown Pointer Types
|
1077
pointer. This stems from having created a pointer (ptrArrayOfNewBrushPtrs) that ini-
tially points to the first element in an array of pointers. To be able to dereference this
pointer to get to the value that the array element is pointing to, you must derefer-
ence it once to get to the array element and then a second time to get the value that
the element is pointing to.
See Also
See the “Unsafe Code Tutorial” topic in the MSDN documentation.
19.7 Switching Unknown Pointer Types
Problem
You need a generic method that accepts two pointers and switches the addresses that
each pointer points to. In other words, if
x points to an integer variable Foo and y
points to an integer variable Bar, you want to switch x so that it points to Bar and
switch
y so that it points to Foo.
Solution
Create a method that accepts two void pointers. The following method accepts two
pointers to
void by reference. The by reference is required since you are actually
switching the values contained in the pointer variables, not the value that the pointer
is pointing to:
public unsafe void Switch(ref void* x, ref void* y)
{
void* temp = x;
x = y;
y = temp;
}
The following test code calls the Switch method with two integer variables that point
to different memory locations:
public unsafe ...