Is it safe to clear managed object references from unmanaged code? #51567
-
Because of the write barrier required for the generational GC, usually we are not allowed to modify managed object references from unmanaged code. However, I think as a special case, clearing references to null from unmanaged code should be safe? Assuming the object containing the reference is on stack or pinned first. For example: ManagedType m = new() { B = new object() };
unsafe
{
nint* ptr = &m.A;
ptr[1] = 0; //Clear m.B
}
struct ManagedType
{
public nint A;
public object B;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Assuming GC thread is going to do compact phase, and thus moving the reference. The moving and clearing may be in a race condition. Since pointer sizes are naturally atomic, the memory will probably not be corrupt, but it may be unreliable that GC move writes after cleaning, making the reference not really cleared. |
Beta Was this translation helpful? Give feedback.
Assuming GC thread is going to do compact phase, and thus moving the reference. The moving and clearing may be in a race condition. Since pointer sizes are naturally atomic, the memory will probably not be corrupt, but it may be unreliable that GC move writes after cleaning, making the reference not really cleared.