Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

We have similar code to the following in one of our projects. Can anyone explain (in simple English) why the fixed statement is needed here?

class TestClass
{
    int iMyVariable;
    static void Main()
    {
        TestClass oTestClass = new TestClass();
        unsafe
        {
            fixed (int* p = &oTestClasst.iMyVariable)
            {
                *p = 9;
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
971 views
Welcome To Ask or Share your Answers For Others

1 Answer

It fixes the pointer in memory. Garbage collected languages have the freedom to move objects around memory for efficiency. This is all transparent to the programmer because they don't really use pointers in "normal" CLR code. However, when you do require pointers, then you need to fix it in memory if you want to work with them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...