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):
1
Int[] arr = new int[10];
2![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
GCHandle gch = GCHandle.Alloc(arr, GCHandleType.Pinned);
4![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5
// Platform invoke prevents the array from being garbage
6
// collected before the call ends.
7
SomeUnmanagedMethod((IntPtr)gch);
8![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
9
gch.Free();
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
2
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
4
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
6
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
7
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
8
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
9
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
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.