简体   繁体   中英

How to declare a pointer to a class object in an unsafe block in C#

Can't I declare a pointer variable to my own class object like below?

static void Main() {
    MyClass myClass = new MyClass();
    unsafe {
        fixed (MyClass* pMyClass = &myClass) {
            /// Do Somthing here with pMyClass..
        }
    }
}

This page explains why: https://msdn.microsoft.com/en-us/library/y31yhkeb.aspx

C# does not allow pointers to references:

A pointer cannot point to a reference or to a struct that contains references, because an object reference can be garbage collected even if a pointer is pointing to it. The garbage collector does not keep track of whether an object is being pointed to by any pointer types.

You could argue that the fixed keyword should allow this because it would stop the GC from collecting the object. This may be true, but consider this case:

class Foo {
    public SomeOtherComplicatedClassAllocatedSeparatley _bar;
}

unsafe void Test() {
    Foo foo = new Foo();
    foo._bar = GetComplicatedObjectInstanceFromSomePool();

    fixed(Foo* fooPtr = &foo) {
        // what happens to `_bar`?
    }
}

The fixed keyword cannot overreach into members of whatever has been dereferenced, it has no authority to pin the reference-member _bar .

Now arguably it still should be possible to pin an object that does not contain other reference-members (eg a simple POCO) and it is possible to pin a String instance, but for some reason the C# language designers just decided to prohibit pinning object instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM