嵌套的固定语句 [英] Nested fixed statement

查看:109
本文介绍了嵌套的固定语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a> for fixed 语句:
$ b

According to the C# reference for fixed statement:


fixed语句防止垃圾收集器重新定位一个
的可移动变量。

...

在语句中的代码被执行后,任何固定的变量都是
unpinned并且可以进行垃圾回收。因此,请不要将
指向固定语句之外的那些变量。

The fixed statement prevents the garbage collector from relocating a movable variable.
...
After the code in the statement is executed, any pinned variables are unpinned and subject to garbage collection. Therefore, do not point to those variables outside the fixed statement.

我的问题是,我没有找到在这个页面上,如果我们为同一个变量嵌套 fixed 语句,会是什么?

My question is, what I haven't found on this page, what will be, if we have nested fixed statement for the same variable?

var data = new byte[100];
unsafe
{
    fixed(byte* pData = data)
    {
        //pData points to the "pinned" variable
        fixed(byte* pData2 = data)
        {
            //pData points to the "pinned" variable
            //pData2 points to the "pinned" variable
        }
        //Does pData still point to the "pinned" variable?
    }
}  

上面的代码当然只是为了说明。实际使用可能是递归函数。

the code above is thought of course only for illustration. The practical use could be recursive functions.

推荐答案

这种方式的工作原理与您期望的一样,必然如此。 fixed 属性与指针变量相关联,而不是它所固定的对象。所以在内部的作用域块中有两个变量可以固定数组。接下来的一个是有一个变量可以用来固定它。它仍然是固定的。

This works just the way you'd expect it to work, necessarily so. The fixed property is associated with the pointer variable, not the object that it pins. So inside the inner scope block there are two variables that pin the array. Next one up there is one variable that pins it. It is still pinned.

当你递归时,数组被声明在方法之外,那么将会有更多的变量将它固定。

When you recurse, and the array is declared outside of the method, then there will be a lot more variables that pin it.

体面的心智形象是根据 fixed 为对象初始化GCHandle的假设。你可以为你的对象创建尽可能多的GCHandles,GC不介意。这实际上并不是在运行时发生的, fixed 比GCHandle更有效率。它是变量的一个属性,在像ildasm.exe这样的反汇编器中显示为[固定]。 GC走过堆栈时发现属性,寻找对象引用。

The decent mental image is to work from the assumption that fixed initializes a GCHandle for the object. You can create as many GCHandles for an object as you dare, the GC does not mind. That doesn't actually happen at runtime, fixed is much more efficient than a GCHandle. It is an attribute of the variable, shown as [pinned] in a disassembler like ildasm.exe. The GC discovers the attribute when it walks the stack, looking for object references.

这篇关于嵌套的固定语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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