Take the address of a ref parameter

[亡魂溺海] 提交于 2019-12-10 17:26:00

问题


My code is as follows

class MyClass
{
    static int iField = 42;
    static void Test(ref int arg)
    {
         unsafe
         {
            fixed(void* pField = &iField)
            fixed(void* pArg = &arg)
            {
                Console.WriteLine ("{0},{1}",(int)pArg,(int)pField);
                //output: 165451772,165451772
            }
         }
    }

    static void Main()
    {
        Test(ref iField);
    }
}

I'd like to know if taking address of ref parameters is as reliable as it showed above in the test.


回答1:


As far as I know, yes while you are in the fixed block, the GC will not relocate arg. Once outside the fixed block the variable is unpinned and thus subject to relocation by the GC.

About a static struct/class/field keeping it's address fixed in memory, the answer is no. They are subject to relocation as any other object. There is not garantee per se that there will be no future relocation in memory just because it is marked as static.

The significance of static has to do with the knowledge and certainties the compiler has at compile time of a certain class/struct/field what have you. It has nothing to do with memory locations and them being fixed or not, etc. In Eric Lippert's words:

Static methods are called “static” because it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.



来源:https://stackoverflow.com/questions/6870474/take-the-address-of-a-ref-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!