@@ -184,11 +184,20 @@ public static void Initialize(IEnumerable<string> args, bool setSysArgv = true)
184184 // Load the clr.py resource into the clr module
185185 IntPtr clr = Python . Runtime . ImportHook . GetCLRModule ( ) ;
186186 IntPtr clr_dict = Runtime . PyModule_GetDict ( clr ) ;
187+ if ( clr_dict == IntPtr . Zero )
188+ {
189+ throw new PythonException ( ) ;
190+ }
187191
188192 var locals = new PyDict ( ) ;
193+ IntPtr module = IntPtr . Zero ;
189194 try
190195 {
191- IntPtr module = Runtime . PyImport_AddModule ( "clr._extras" ) ;
196+ module = Runtime . PyImport_AddModule ( "clr._extras" ) ;
197+ if ( module == IntPtr . Zero )
198+ {
199+ throw new PythonException ( ) ;
200+ }
192201 IntPtr module_globals = Runtime . PyModule_GetDict ( module ) ;
193202 IntPtr builtins = Runtime . PyEval_GetBuiltins ( ) ;
194203 Runtime . PyDict_SetItemString ( module_globals , "__builtins__" , builtins ) ;
@@ -205,7 +214,8 @@ public static void Initialize(IEnumerable<string> args, bool setSysArgv = true)
205214 // add the imported module to the clr module, and copy the API functions
206215 // and decorators into the main clr module.
207216 Runtime . PyDict_SetItemString ( clr_dict , "_extras" , module ) ;
208- foreach ( PyObject key in locals . Keys ( ) )
217+ using ( PyObject keys = locals . Keys ( ) )
218+ foreach ( PyObject key in keys )
209219 {
210220 if ( ! key . ToString ( ) . StartsWith ( "_" ) || key . ToString ( ) . Equals ( "__version__" ) )
211221 {
@@ -219,6 +229,10 @@ public static void Initialize(IEnumerable<string> args, bool setSysArgv = true)
219229 finally
220230 {
221231 locals . Dispose ( ) ;
232+ if ( clr != IntPtr . Zero )
233+ {
234+ Runtime . Py_DecRef ( clr ) ;
235+ }
222236 }
223237 }
224238 }
@@ -496,7 +510,7 @@ internal static PyObject RunString(string code, IntPtr? globals, IntPtr? locals,
496510 borrowedGlobals = false ;
497511 }
498512 }
499-
513+
500514 if ( locals == null )
501515 {
502516 locals = globals ;
@@ -552,7 +566,7 @@ public static PyScope CreateScope(string name)
552566 var scope = PyScopeManager . Global . Create ( name ) ;
553567 return scope ;
554568 }
555-
569+
556570 public class GILState : IDisposable
557571 {
558572 private IntPtr state ;
@@ -649,7 +663,7 @@ public static void SetArgv(IEnumerable<string> argv)
649663
650664 public static void With ( PyObject obj , Action < dynamic > Body )
651665 {
652- // Behavior described here:
666+ // Behavior described here:
653667 // https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers
654668
655669 IntPtr type = Runtime . PyNone ;
0 commit comments