this is the 2nd part of the 1st question using c# pointers
so pointers in c# are ‘unsafe’ and not managed by the garbage collector while an IntPtr is a managed object. but why use pointers then? and when it is possible to use both approaches interchangeably?
The CLI distinguishes between managed and unmanaged pointers. A managed pointer is typed, the type of the pointed-to value is known by the runtime and only type-safe assignments are allowed. Unmanaged pointers are only directly usable in a language that supports them, C++/CLI is the best example.
The equivalent of an unmanaged pointer in the C# language is
IntPtr. You can freely convert a pointer back and forth with a cast. No pointer type is associated with it even though its name sounds like “pointer to int”, it is the equivalent ofvoid*in C/C++. Using such a pointer requires pinvoke, the Marshal class or a cast to a managed pointer type.Some code to play with:
Note how the
unsafekeyword is appropriate here. You can call Marshal.WriteInt64() and you get no complaint whatsoever. It corrupts the stack frame.