Search code examples
c#pointersintptr

Why can't we take a pointer to a string?


With the following codes:

static unsafe void Main( string[] args )
{
  int a = 5;
  IntPtr pa = new IntPtr( &a );  // no error
  var xa =  pa.ToPointer();

  string b = "test";
  IntPtr pb = new IntPtr( &b );   // compile error
  var xb = pb.ToPointer();
}

It generate compile error:

Cannot take the address of, get the size of, or declare a pointer to a managed type ('type')

What's wrong with having a pointer to a managed type?


Solution

  • The reason is that managed objects can be moved around in memory as a side-effect of garbage collection of other objects, thus invalidating any pointers to them.

    The int you are taking the address of is on the stack, and will not be moved around in memory - thus it is safe to access a pointer to it. (Well, as safe as using pointers can be...)