简体   繁体   English

C#不安全指针字段

[英]C# unsafe pointer fields

Is this going to break? 这会破裂吗? It compiles fine but based on readings, I'm unsure if its guaranteed that _ptRef will always point to the struct referenced in the constructor. 它可以编译,但是基于读数,我不确定它是否保证_ptRef始终指向构造函数中引用的结构。

I guess by 'break' I mean...will the GC move the struct pointed to by the pointer (_ptRef)? 我猜是“中断”,我的意思是……GC是否会移动指针(_ptRef)指向的结构?

public unsafe class CPointType0
{
    private PointType0* _ptRef = null;

    public CPointType0(ref PointType0 spt)
    {
        fixed (PointType0 * pt = &spt)
        {
            _ptRef = pt;
        }
    }

...a bunch of property accessors to fields of _ptRef (accessed as return _ptRef->Thing) }

The scenario is 该方案是

-PointType0 is a struct. -PointType0是一个结构。

-millions of PointType0's in memory in a data structure. 数据结构中的数百万个PointType0。 These used to be reference types but there gets to be way too much memory overhead. 这些曾经是引用类型,但是会有太多的内存开销。

-A List is returned only when a search operation finds a relevant PointType0, and this List is passed around and operated on a lot. -仅当搜索操作找到相关的PointType0时才返回List,并且此List会被传递并对其进行大量操作。

It's not safe. 不安全

After the code leaves the fixed block, the garbage collector is free to move things around again. 代码离开fixed块后,垃圾收集器可以自由移动其他内容。 What are you trying to accomplish here? 您想在这里完成什么? Do you maybe want to use the index of an item in the list, instead of a pointer? 您是否要使用列表中项目的索引,而不是指针?

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

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