GCHandle.FromIntPointer 没有按预期工作 [英] GCHandle.FromIntPointer does not work as expected
问题描述
这是一个非常简单(完整)的程序,用于练习 GCHandle.FromIntPointer 的使用:
Here's a very simple (complete) program for exercising the use of 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);
}
}
}
请注意,该程序本质上是对 CLR via C# (4e) 在第 547 页.但是,运行它会导致非托管异常,例如:
Note that this program is essentially a transliteration of the procedure described in English on CLR via C# (4e) on page 547. Running it, however, results in an unmanaged exception like:
附加信息:运行时遇到致命错误.错误地址位于线程 0x21bc 上的 0x210bc39b.错误代码是 0xc0000005.此错误可能是 CLR 或用户代码的不安全或不可验证部分中的错误.此错误的常见来源包括 COM 互操作或 PInvoke 的用户封送错误,这可能会损坏堆栈.
认为这可能是 .NET 4.5 中的一个错误,并且由于我没有发现任何明显错误,我在 Linux (v2.10.8.1) 上的 Mono 中尝试了完全相同的程序.我得到了信息量稍多但仍然令人费解的异常 GCHandle 值属于不同的域.
Thinking that this might be a bug in .NET 4.5, and since I don't see anything obviously wrong, I tried exactly the same program in Mono on Linux (v2.10.8.1). I got the slightly more informative but still puzzling exception GCHandle value belongs to a different domain.
据我所知,handle
确实与我调用 GCHandle.FromIntPtr
的代码属于同一个 AppDomain.但是我在两个实现中都看到异常的事实让我怀疑我遗漏了一些重要的细节.这是怎么回事?
As far as I am aware, the handle
really does belong to the same AppDomain as the code where I call GCHandle.FromIntPtr
. But the fact that I see an exception in both implementations makes me suspect that I am missing some important detail. What's going on here?
推荐答案
AddrOfPinnedObject
不是 FromIntPtr
的对立面.你想要 ToIntPtr
代替:
AddrOfPinnedObject
is not the opposite of FromIntPtr
. You want ToIntPtr
instead:
IntPtr pointer = handle.ToIntPtr ();
GCHandle handle2 = GCHandle.FromIntPtr (pointer);
FromIntPtr
不取对象的地址,它取一个不透明的值(恰好定义为 IntPtr),用于检索带有 ToIntPtr
.
FromIntPtr
does not take the address of the object, it takes an opaque value (which happens to be defined as IntPtr), which is used to retrieve the object with ToIntPtr
.
这篇关于GCHandle.FromIntPointer 没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!