Blittable and Non-Blittable,P/Invoke,Heap Crash,Marshal

Most common cause of CLR crash is managed heaps corruption which often occurs in P/Invoke application. When unmanage code tries to access managed object which has been free or relocated in memory when memory is reclaimed by GC , it's corrupting the managed heap.  To pin a object in memory , GCHandles come in.

The syntax for allocating a pinned GCHandle is as follows (C# code):

1Int[] arr = new int[10];
2
3GCHandle gch = GCHandle.Alloc(arr, GCHandleType.Pinned);
4
5      // Platform invoke prevents the array from being garbage 
6      // collected before the call ends.
7      SomeUnmanagedMethod((IntPtr)gch);
8
9gch.Free();

Note: you can only pin blittable types in memory (types that have the same representation in managed and unmanaged code).  Blittable types include primitive types and arrays.

This GCHandle must be released with Free when it is no longer needed.

 

posted @ 2008-10-08 22:36  octoberfirst  阅读(476)  评论(1编辑  收藏  举报