C
C#β€’2y ago
Dusty

βœ… 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
nukleer bomb
nukleer bombβ€’2y ago
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)
Aaron
Aaronβ€’2y ago
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
Sample sample = new();
WeakReference weakRef = new(sample);
sample = null;
// weakRef.IsAlive will now tell you if the object sample used to point to has been collected
Sample sample = new();
WeakReference weakRef = new(sample);
sample = null;
// weakRef.IsAlive will now tell you if the object sample used to point to has been collected
i would highly encourage avoiding the Unsafe class unless you understand references in C#
Dusty
Dustyβ€’2y ago
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
Aaron
Aaronβ€’2y ago
you can't store pointers to objects you would have no way to know if the GC moved one of them
Dusty
Dustyβ€’2y ago
Hmm that's what i thoght Well ig I've to use weak refs thenπŸ˜