@@ -23,6 +23,16 @@ internal static void InitializeModuleDef()
2323 module_def = ModuleDefOffset . AllocModuleDef ( "clr" ) ;
2424 }
2525 }
26+
27+ internal static void ReleaseModuleDef ( )
28+ {
29+ if ( module_def == IntPtr . Zero )
30+ {
31+ return ;
32+ }
33+ ModuleDefOffset . FreeModuleDef ( module_def ) ;
34+ module_def = IntPtr . Zero ;
35+ }
2636#endif
2737
2838 /// <summary>
@@ -56,9 +66,12 @@ static void InitImport()
5666 // Python __import__.
5767 IntPtr builtins = GetNewRefToBuiltins ( ) ;
5868 py_import = Runtime . PyObject_GetAttrString ( builtins , "__import__" ) ;
69+ PythonException . ThrowIfIsNull ( py_import ) ;
70+
5971 hook = new MethodWrapper ( typeof ( ImportHook ) , "__import__" , "TernaryFunc" ) ;
60- Runtime . PyObject_SetAttrString ( builtins , "__import__" , hook . ptr ) ;
61- Runtime . XDecref ( hook . ptr ) ;
72+ int res = Runtime . PyObject_SetAttrString ( builtins , "__import__" , hook . ptr ) ;
73+ PythonException . ThrowIfIsNotZero ( res ) ;
74+
6275 Runtime . XDecref ( builtins ) ;
6376 }
6477
@@ -69,10 +82,14 @@ static void RestoreImport()
6982 {
7083 IntPtr builtins = GetNewRefToBuiltins ( ) ;
7184
72- Runtime . PyObject_SetAttrString ( builtins , "__import__" , py_import ) ;
85+ int res = Runtime . PyObject_SetAttrString ( builtins , "__import__" , py_import ) ;
86+ PythonException . ThrowIfIsNotZero ( res ) ;
7387 Runtime . XDecref ( py_import ) ;
7488 py_import = IntPtr . Zero ;
7589
90+ hook . Release ( ) ;
91+ hook = null ;
92+
7693 Runtime . XDecref ( builtins ) ;
7794 }
7895
@@ -112,13 +129,26 @@ internal static void Initialize()
112129 /// </summary>
113130 internal static void Shutdown ( )
114131 {
115- if ( Runtime . Py_IsInitialized ( ) ! = 0 )
132+ if ( Runtime . Py_IsInitialized ( ) = = 0 )
116133 {
117- RestoreImport ( ) ;
134+ return ;
135+ }
118136
119- Runtime . XDecref ( py_clr_module ) ;
120- Runtime . XDecref ( root . pyHandle ) ;
137+ RestoreImport ( ) ;
138+
139+ bool shouldFreeDef = Runtime . Refcount ( py_clr_module ) == 1 ;
140+ Runtime . XDecref ( py_clr_module ) ;
141+ py_clr_module = IntPtr . Zero ;
142+ #if PYTHON3
143+ if ( shouldFreeDef )
144+ {
145+ ReleaseModuleDef ( ) ;
121146 }
147+ #endif
148+
149+ Runtime . XDecref ( root . pyHandle ) ;
150+ root = null ;
151+ CLRModule . Reset ( ) ;
122152 }
123153
124154 /// <summary>
0 commit comments