GCHandle.FromIntPointer不能按预期工作 [英] GCHandle.FromIntPointer does not work as expected

查看:164
本文介绍了GCHandle.FromIntPointer不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单(完整)的程序,用于练习使用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通过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:

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.

认为这可能是.NET 4.5中的错误,并且由于我没有发现明显的错误,因此我在Linux(v2.10.8.1)上的Mono中尝试了完全相同的程序.我得到了更多一些信息,但仍然令人困惑的异常GCHandle value belongs to a different domain.

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?

推荐答案

AddrOfPinnedObjectFromIntPtr相反.您需要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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆