WolfOdrade
WolfOdrade

Reputation: 370

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.

I guess by 'break' I mean...will the GC move the struct pointed to by the pointer (_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.

-millions of PointType0's in memory in a data structure. 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.

Upvotes: 2

Views: 764

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415921

It's not safe.

After the code leaves the fixed block, the garbage collector is free to move things around again. 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?

Upvotes: 6

Related Questions