diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index 902d8c734..3c7f13ec6 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -157,6 +157,7 @@ public T As() return (T)AsManagedObject(typeof(T)); } + internal bool IsDisposed => obj == IntPtr.Zero; /// /// Dispose Method diff --git a/src/runtime/pyscope.cs b/src/runtime/pyscope.cs index 72cb9f247..9d68b76fa 100644 --- a/src/runtime/pyscope.cs +++ b/src/runtime/pyscope.cs @@ -29,18 +29,15 @@ public class PyScope : DynamicObject, IDisposable /// /// the python Module object the scope associated with. /// - internal IntPtr obj; - internal BorrowedReference Reference => new BorrowedReference(obj); + readonly PyObject obj; + internal BorrowedReference Reference => obj.Reference; /// - /// the variable dict of the scope. + /// the variable dict of the scope. Borrowed. /// internal readonly IntPtr variables; internal BorrowedReference VarsRef => new BorrowedReference(variables); - private bool _isDisposed; - private bool _finalized = false; - /// /// The Manager this scope associated with. /// It provides scopes this scope can import. @@ -65,7 +62,7 @@ internal PyScope(ref NewReference ptr, PyScopeManager manager) throw new PyScopeException("object is not a module"); } Manager = manager ?? PyScopeManager.Global; - obj = ptr.DangerousMoveToPointer(); + obj = ptr.MoveToPyObject(); //Refcount of the variables not increase variables = Runtime.PyModule_GetDict(Reference).DangerousGetAddress(); PythonException.ThrowIfIsNull(variables); @@ -81,7 +78,6 @@ internal PyScope(ref NewReference ptr, PyScopeManager manager) /// /// return the variable dict of the scope. /// - /// public PyDict Variables() { Runtime.XIncref(variables); @@ -136,7 +132,7 @@ public dynamic Import(string name, string asname = null) /// public void Import(PyScope scope, string asname) { - this.Set(asname, scope.obj); + this.SetPyValue(asname, scope.obj.Handle); } /// @@ -335,11 +331,11 @@ private void Exec(string code, BorrowedReference _globals, BorrowedReference _lo public void Set(string name, object value) { IntPtr _value = Converter.ToPython(value, value?.GetType()); - Set(name, _value); + SetPyValue(name, _value); Runtime.XDecref(_value); } - private void Set(string name, IntPtr value) + private void SetPyValue(string name, IntPtr value) { Check(); using (var pyKey = new PyString(name)) @@ -507,7 +503,7 @@ public override bool TrySetMember(SetMemberBinder binder, object value) private void Check() { - if (_isDisposed) + if (this.obj.IsDisposed) { throw new PyScopeException($"The scope of name '{Name}' object has been disposed"); } @@ -515,23 +511,8 @@ private void Check() public void Dispose() { - if (_isDisposed) - { - return; - } - _isDisposed = true; - Runtime.XDecref(obj); this.OnDispose?.Invoke(this); - } - - ~PyScope() - { - if (_finalized || _isDisposed) - { - return; - } - _finalized = true; - Finalizer.Instance.AddFinalizedObject(ref obj); + this.obj.Dispose(); } }