File tree Expand file tree Collapse file tree 3 files changed +28
-5
lines changed Expand file tree Collapse file tree 3 files changed +28
-5
lines changed Original file line number Diff line number Diff line change @@ -35,13 +35,13 @@ internal CLRObject(object ob, IntPtr tp)
35
35
}
36
36
37
37
38
- internal static CLRObject GetInstance ( object ob , IntPtr pyType )
38
+ static CLRObject GetInstance ( object ob , IntPtr pyType )
39
39
{
40
40
return new CLRObject ( ob , pyType ) ;
41
41
}
42
42
43
43
44
- internal static CLRObject GetInstance ( object ob )
44
+ static CLRObject GetInstance ( object ob )
45
45
{
46
46
ClassBase cc = ClassManager . GetClass ( ob . GetType ( ) ) ;
47
47
return GetInstance ( ob , cc . tpHandle ) ;
Original file line number Diff line number Diff line change @@ -188,7 +188,29 @@ protected virtual void Dispose(bool disposing)
188
188
189
189
if ( ! Runtime . IsFinalizing )
190
190
{
191
- Runtime . XDecref ( this . obj ) ;
191
+ long refcount = Runtime . Refcount ( this . obj ) ;
192
+ Debug . Assert ( refcount > 0 , "Object refcount is 0 or less" ) ;
193
+
194
+ if ( refcount == 1 )
195
+ {
196
+ Runtime . PyErr_Fetch ( out var errType , out var errVal , out var traceback ) ;
197
+
198
+ try
199
+ {
200
+ Runtime . XDecref ( this . obj ) ;
201
+ Runtime . CheckExceptionOccurred ( ) ;
202
+ }
203
+ finally
204
+ {
205
+ // Python requires finalizers to preserve exception:
206
+ // https://docs.python.org/3/extending/newtypes.html#finalization-and-de-allocation
207
+ Runtime . PyErr_Restore ( errType , errVal , traceback ) ;
208
+ }
209
+ }
210
+ else
211
+ {
212
+ Runtime . XDecref ( this . obj ) ;
213
+ }
192
214
}
193
215
this . obj = IntPtr . Zero ;
194
216
}
Original file line number Diff line number Diff line change 1
1
using System ;
2
+ using System . Diagnostics . Contracts ;
2
3
using System . Runtime . InteropServices ;
3
4
using System . Security ;
4
5
using System . Text ;
8
9
9
10
namespace Python . Runtime
10
11
{
11
-
12
12
/// <summary>
13
13
/// Encapsulates the low-level Python C API. Note that it is
14
14
/// the responsibility of the caller to have acquired the GIL
@@ -106,7 +106,7 @@ public class Runtime
106
106
internal static object IsFinalizingLock = new object ( ) ;
107
107
internal static bool IsFinalizing ;
108
108
109
- internal static bool Is32Bit = IntPtr . Size == 4 ;
109
+ internal static bool Is32Bit => IntPtr . Size == 4 ;
110
110
111
111
// .NET core: System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
112
112
internal static bool IsWindows = Environment . OSVersion . Platform == PlatformID . Win32NT ;
@@ -659,6 +659,7 @@ internal static unsafe void XDecref(IntPtr op)
659
659
#endif
660
660
}
661
661
662
+ [ Pure ]
662
663
internal static unsafe long Refcount( IntPtr op )
663
664
{
664
665
var p = ( void * ) op ;
You can’t perform that action at this time.
0 commit comments