16.7. Creating and Using an Array of Pointersto Unknown Types
Problem
You need to create and operate on elements of an array that holds objects of unknown types.
Solution
The solution
is to create an array of void
pointers so that we
do not need to know at design time what type(s) we will be pointing
to:
unsafe { long x = 10; long y = 20; long z = 1; void*[] arrayOfPtrs = new void*[3]; arrayOfPtrs[0] = &X; arrayOfPtrs[1] = &Y; arrayOfPtrs[2] = &Z; Console.WriteLine(*((long*)arrayOfPtrs[0])); Console.WriteLine(*((long*)arrayOfPtrs[1])); Console.WriteLine(*((long*)arrayOfPtrs[2])); }
This code creates an array, arrayOfPtrs
, that will
contain three void
pointers. The pointers that are
saved to this array are pointers to the three variables
x
, y
, and z
of type long
. It is a simple matter to change the
long
data type to something different such as a
byte
or char
. However, when the
pointers in this array are used, they must be cast back to their
original type. This cast is shown in the last three lines, where each
pointer in the array is being dereferenced and displayed. If you do
the wrong cast, you get undefined results, but the next example helps
address this.
The following code creates an array of two void
pointers and points the first pointer at a
NewBrush
structure and the second at an integer
type variable:
unsafe { NewBrush theNewBrush1 = new NewBrush( ); int* theInt = stackalloc int[1]; void*[] arrayOfPtrs = new void*[2]; arrayOfPtrs[0] = &theNewBrush1; arrayOfPtrs[1] = theInt; ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.