The CLI distinguishes between managed and unmanaged pointers. A managed pointer is typed, the type of point value is known at run time, and only safe assignment types are allowed. Unmanaged pointers are only directly used in a language that supports them, C ++ / CLI is the best example.
The equivalent of an unmanaged pointer in C # is IntPtr . You can freely convert the pointer back and forth with cast. The pointer type is not associated with it, although its name sounds like a "pointer to int", this is equivalent to void* in C / C ++. Using such a pointer requires pinvoke, a marshal class, or cast to a managed pointer type.
Some code to play:
using System; using System.Runtime.InteropServices; unsafe class Program { static void Main(string[] args) { int variable = 42; int* p = &variable; Console.WriteLine(*p); IntPtr raw = (IntPtr)p; Marshal.WriteInt32(raw, 666); p = (int*)raw; Console.WriteLine(*p); Console.ReadLine(); } }
Please note that the unsafe keyword is suitable here. You can call Marshal.WriteInt64 () and you will not receive any complaint. It corrupts the stack frame.
Hans passant
source share