tags:

views:

46

answers:

1

how do CLR interact with unsafe code I found various result on Google but i couldn't understand. I am also confused that is Garbage collector work on unsafe code? if yes than how?

I cant point pointer to Array,s first element I try this code

unsafe{

  int[] a = { 4, 5 };
  int* b = a;
  }

but I got that error Error :Cannot implicitly convert type 'int[]' to 'int*'

+1  A: 

No reason why the garbage collector wouldn't work on unsafe code. I'm assuming you're talking about pointers to pinned objects, like:

int[] arr = new int[100];
unsafe
{
     fixed (int* p = arr)
     { 
          // use p
     }
}

At the end of the block p is unaccesible anymore, so it can be safely collected.

Now... this isn't always true. You might pass the pointer to other functions and then exit the block (the EnumWindows family of functions come to mind where you give them a pointer to a structure and then can be done with the function you're in, they handle the rest themselves).

The GC.KeepAlive "function" (read hack) is used to handle this case by holding the variable in scope until you're really done with it -- that's right, it does nothing except trick the GC into thinking you're still using the reference.

Blindy
Error: Cannot convert type 'int[]' to 'int*' plz correct this
Govind KamalaPrakash Malviya
My bad forgot I had to actually pin the thing down. Been a while..
Blindy