β Is managed pointer (ref) or raw pointer (void*) null?
How can I check if a managed pointer or raw pointer points to an already garbage collected address?
```cs
var sample = new Sample();
ref var refToSample = ref Unsafe.AsRef(in sample);
sample = null;
// How to check if sample got garbage collected?
// this is false
bool isNullRef = Unsafe.IsNullRef(ref refToSample);
// How to check if the value the pointer is pointing at is garbage collected?
void* ptr = Unsafe.AsPointer(ref refToSample);
5 Replies
There is
Unsafe.IsNullRef<T>(ref T)
for managed pointers
And rawPtr == null
for raw ones
When you point to an address in managed memory, runtime guarantees that this memory will not be garbage-collected while you use the pointer.
And, in your example, both refToSample
and ptr
points to sample
variable, not to Sample
instance itself (assuming that Sample
is class
)uh
this doesnt do what you think it does
refToSample is never null here
its a reference to the local
sample
, which you set to null, but that is different than the reference to sample
being null
pretty sure you're looking for WeakReferences
i would highly encourage avoiding the Unsafe class unless you understand references in C#I thought it only does so if the object is pinned?
And i tested around a bit, the object can get garbage collected while having the ref to it
Actually for an alternative
I wanna store pointers in an array an need to know which ones are still active/not garbage collected yet
you can't store pointers to objects
you would have no way to know if the GC moved one of them
Hmm that's what i thoght
Well ig I've to use weak refs thenπ