11namespace Python . Runtime
22{
33 using System ;
4+ using System . Diagnostics . Contracts ;
5+
46 /// <summary>
57 /// Represents a reference to a Python object, that is tracked by Python's reference counting.
68 /// </summary>
79 [ NonCopyable ]
810 ref struct NewReference
911 {
1012 IntPtr pointer ;
11- public bool IsNull => this . pointer == IntPtr . Zero ;
12-
13- /// <summary>Gets a raw pointer to the Python object</summary>
14- public IntPtr DangerousGetAddress ( )
15- => this . IsNull ? throw new NullReferenceException ( ) : this . pointer ;
1613
1714 /// <summary>
1815 /// Returns <see cref="PyObject"/> wrapper around this reference, which now owns
1916 /// the pointer. Sets the original reference to <c>null</c>, as it no longer owns it.
2017 /// </summary>
2118 public PyObject MoveToPyObject ( )
2219 {
23- if ( this . IsNull ) throw new NullReferenceException ( ) ;
20+ if ( this . IsNull ( ) ) throw new NullReferenceException ( ) ;
2421
2522 var result = new PyObject ( this . pointer ) ;
2623 this . pointer = IntPtr . Zero ;
@@ -31,9 +28,32 @@ public PyObject MoveToPyObject()
3128 /// </summary>
3229 public void Dispose ( )
3330 {
34- if ( ! this . IsNull )
31+ if ( ! this . IsNull ( ) )
3532 Runtime . XDecref ( this . pointer ) ;
3633 this . pointer = IntPtr . Zero ;
3734 }
35+
36+ [ Pure ]
37+ internal static IntPtr DangerousGetAddress ( in NewReference reference )
38+ => IsNull ( reference ) ? throw new NullReferenceException ( ) : reference . pointer ;
39+ [ Pure ]
40+ internal static bool IsNull ( in NewReference reference )
41+ => reference . pointer == IntPtr . Zero ;
42+ }
43+
44+ /// <summary>
45+ /// These members can not be directly in <see cref="NewReference"/> type,
46+ /// because <c>this</c> is always passed by value, which we need to avoid.
47+ /// (note <code>this in NewReference</code> vs the usual <code>this NewReference</code>)
48+ /// </summary>
49+ static class NewReferenceExtensions
50+ {
51+ /// <summary>Gets a raw pointer to the Python object</summary>
52+ [ Pure ]
53+ public static IntPtr DangerousGetAddress ( this in NewReference reference )
54+ => NewReference . DangerousGetAddress ( reference ) ;
55+ [ Pure ]
56+ public static bool IsNull ( this in NewReference reference )
57+ => NewReference . IsNull ( reference ) ;
3858 }
3959}
0 commit comments