Create and access a heterogeneous pointer array
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| C# Code Snippets |
| See also |
| edit |
This C# code snippet creates an unsafe heteropointer array containing the addresses of various data types. Then, it uses the pointer array to access the heterogeneous types.
WARNING: DO NOT PLAY WITH UNSAFE CODE. If you do not know what you are doing, you can cause any number of costly problems. Use this code at your own risk. They don't call it unsafe for nothing.
class UnsafePointerArray { public struct AStruct { public int anInteger; } public static void CreatePointerArray() { unsafe { char ch; AStruct struct0 = new AStruct(); int* theInt = stackalloc int[1]; void*[] pointerArray = new void*[3]; pointerArray[0] = &ch; pointerArray[1] = &struct0; pointerArray[2] = theInt; *((char*) pointerArray[0]) = 'a'; ((AStruct*) pointerArray[1])->anInteger = 20; *((int*) pointerArray[2]) = 30; Console.WriteLine ("pointerArray[0] = " + ((char*) pointerArray[0])->ToString()); Console.WriteLine ("pointerArray[1] = " + ((AStruct*) pointerArray[1])->anInteger); Console.WriteLine ("pointerArray[2] = " + ((int*) pointerArray[2])->ToString()); } } }
| Unsafe Pointer Array (program output) |
| pointerArray[0] = a pointerArray[1] = 20 pointerArray[2] = 30 |
[edit]