简体   繁体   English

如何在C#中的不安全块中声明指向类对象的指针

[英]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 本页说明原因: https : //msdn.microsoft.com/zh-cn/library/y31yhkeb.aspx

C# does not allow pointers to references: C#不允许指向引用的指针:

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. 您可能会争辩说fixed关键字应该允许这样做,因为它将阻止GC收集对象。 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 . fixed关键字不能扩展到已取消引用的任何成员,它无权固定引用成员_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. 现在可以说,仍然可以固定不包含其他引用成员的对象(例如,简单的POCO),并且可以固定String实例,但是由于某些原因,C#语言设计者只是决定禁止固定对象实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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