@@ -503,15 +503,19 @@ private static void PyDictTryDelItem(BorrowedReference dict, string key)
503503 private static void MoveClrInstancesOnwershipToPython ( )
504504 {
505505 var objs = ManagedType . GetManagedObjects ( ) ;
506- var copyObjs = objs . ToArray ( ) ;
507- foreach ( var entry in copyObjs )
506+ var copyObjs = new KeyValuePair < ManagedType , ManagedType . TrackTypes > [ objs . Count ] ;
508507 {
509- ManagedType obj = entry . Key ;
510- if ( ! objs . ContainsKey ( obj ) )
508+ int i = 0 ;
509+ foreach ( var entry in objs )
511510 {
512- System . Diagnostics . Debug . Assert ( obj . gcHandle == default ) ;
513- continue ;
511+ ManagedType obj = entry . Key ;
512+ XIncref ( obj . pyHandle ) ;
513+ copyObjs [ i ++ ] = entry ;
514514 }
515+ }
516+ foreach ( var entry in copyObjs )
517+ {
518+ ManagedType obj = entry . Key ;
515519 if ( entry . Value == ManagedType . TrackTypes . Extension )
516520 {
517521 obj . CallTypeClear ( ) ;
@@ -522,8 +526,21 @@ private static void MoveClrInstancesOnwershipToPython()
522526 PyObject_GC_Track ( obj . pyHandle ) ;
523527 }
524528 }
525- obj . FreeGCHandle ( ) ;
526- Marshal . WriteIntPtr ( obj . pyHandle , ObjectOffset . magic ( obj . tpHandle ) , IntPtr . Zero ) ;
529+ }
530+ foreach ( var entry in copyObjs )
531+ {
532+ ManagedType obj = entry . Key ;
533+ if ( ! objs . ContainsKey ( obj ) )
534+ {
535+ System . Diagnostics . Debug . Assert ( obj . gcHandle == default ) ;
536+ continue ;
537+ }
538+ if ( obj . RefCount > 1 )
539+ {
540+ obj . FreeGCHandle ( ) ;
541+ Marshal . WriteIntPtr ( obj . pyHandle , ObjectOffset . magic ( obj . tpHandle ) , IntPtr . Zero ) ;
542+ }
543+ XDecref ( obj . pyHandle ) ;
527544 }
528545 ManagedType . ClearTrackedObjects ( ) ;
529546 }
0 commit comments