C # pointers vs IntPtr

this is the second part of the 1st question using C # pointers

therefore, pointers in C # are "unsafe" and are not managed by the garbage collector, and IntPtr is a managed entity. but why use pointers? and when can both approaches be used interchangeably?

+7
pointers c #
source share
4 answers

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.

+7
source share

An IntPtr cannot be used as a pointer replacement.

IntPtr just contains a numeric value, so you cannot use it to access any data. Hence the name; it is an integer value with the same size as the pointer. You need to turn the value into a pointer to access the data it points to, so there is no data access without using unsafe code.

Note that IntPtr is a structure, not an object, so the garbage collector is not directly related to it.

+7
source share

IntPtr is a managed object, but the object it points to is still not garbage collected. Using unsafe pointers in C # is something you should avoid. Code using unsafe pointers may not take into account differences in memory addresses between x86 and x64 systems. This allows you to directly manipulate memory addresses, which is not the case with IntPtr, since you will need to march between the pointer and the actual structure stored on that memory address. Using unsafe pointers, you can directly work with the base type: here I wrote a blog post illustrating one possible use of unsafe pointers. Another common example is manipulating the pixels of an image directly.

+5
source share

The dereferencing data that IntPtr points to is simply sticking the IntPtr number to the unsafe ptr address, as shown below

 unsafe{ IntPtr p = new MyStruct("fred"); myStruct * sptr; sptr=p; Console.WriteLine(*sptr->name); } 
+2
source share

All Articles