Here's a very simple (complete) program for using GCHandle.FromIntPointer:
using System; using System.Runtime.InteropServices; namespace GCHandleBugTest { class Program { static void Main(string[] args) { int[] arr = new int[10]; GCHandle handle = GCHandle.Alloc(arr, GCHandleType.Pinned); IntPtr pointer = handle.AddrOfPinnedObject(); GCHandle handle2 = GCHandle.FromIntPtr(pointer); } } }
Note that this program is essentially a transliteration of the procedure described in English on the CLR through C # (4e) on page 547. Running it, however, leads to an unmanaged exception, for example:
Additional Information: The runtime has encountered a fatal error. The address of the error was at 0x210bc39b, on thread 0x21bc. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
Thinking that this could be a mistake in .NET 4.5, and since I see nothing obviously wrong, I tried the exact same program in Mono on Linux (v2.10.8.1). I got a slightly more informative but still cryptic exception for the GCHandle value belongs to a different domain.
As far as I know, handle really belongs to the same AppDomain as the code in which I call GCHandle.FromIntPtr . But the fact that I see an exception in both implementations makes me suspect that I am missing some important details. What's going on here?
source share