Take the address of a ref parameter

2019-06-24 00:19发布

问题:

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.



标签: c# unsafe