c# - 如何在其方法中获取结构的地址?

标签 c# pointers struct garbage-collection

我能够在其(实例)方法之外获取结构的地址,如下所示:

public struct Values
{
    public byte A;
    public byte B;
    public byte C;
    public byte D;

    public static unsafe bool Equals(Values lhs, Values rhs)
    {
        return *(int*) &lhs == *(int*) &rhs;
    }
}

但是当我尝试获取结构本身的地址时,IDE 告诉我这是错误的:

    public unsafe bool Equals(Values other)
    {
        return *(int*) &this == *(int*) &other;
    }

错误信息是:

You can only take the address of an unfixed expression inside of a fixed statement initializer.

fixed 语句防止垃圾收集器重定位可移动变量。 但是这个结构不是可移动变量,不会被垃圾回收,对吧?

已更新

我实际需要的是通过索引获取/设置第 N 个字节的值。虽然我可以通过 switch 语句来完成,但是通过索引会更快。 感谢@KonradKokosa,Fixed Size Buffer满足我的需求。 我仍然想知道主要问题的答案。

最佳答案

您不能在结构实例方法中获取 this 的地址,因为 “this struct is not a movable variable” 不是真实的陈述。结构可以装箱,因此它立即变得可移动。实例方法不知道它是从装箱结构还是非装箱结构中调用的。

请注意,它目前也是 ref struct 的长期限制,尽管它可以解除。所以,下面的代码仍然会产生相同的编译错误:

public ref struct C {
    public void M() {
        var ptr = &this;
    }
}

但是,您可以在第一个片段中获取结构的地址:

public static unsafe bool Equals(Values lhs, Values rhs)
{
    return *(int*) &lhs == *(int*) &rhs;
}

因为您在这里获取局部参数的地址,按值传递(最后是 Values 的副本)。

关于c# - 如何在其方法中获取结构的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64112247/

相关文章:

c - 在结构定义中的 ' ' 标记之前应为 '='

c# - 为什么要在 Method<type>() 中指定 <type> ?以及如何使用它?

c# - 由于图像导致的 Crystal Report 加载问题

C++ 是否可以有一个通用的函数指针?

c - 使用相同的指针询问下一个值

c++ - 打包结构中的解包结构是否自动打包?

c# - 在按钮下放置弹出窗口(UWP、XAML、C#)

c# - 将字符串拆分(不解析)为命令行参数 C#

C++ std::allocator::allocate() 给我一个错误的指针

c++ - Visual Studio 抛出异常 : write acces violation. q_deck->p_deck 为 0x110112。 C语言