@@ -14,6 +14,9 @@ public class PythonEngine : IDisposable
1414 {
1515 private static DelegateManager delegateManager ;
1616 private static bool initialized ;
17+ private static IntPtr _pythonHome = IntPtr . Zero ;
18+ private static IntPtr _programName = IntPtr . Zero ;
19+ private static IntPtr _pythonPath = IntPtr . Zero ;
1720
1821 public PythonEngine ( )
1922 {
@@ -64,7 +67,14 @@ public static string ProgramName
6467
6568 return result ?? "" ;
6669 }
67- set { Runtime . Py_SetProgramName ( value ) ; }
70+ set
71+ {
72+ Marshal . FreeHGlobal ( _programName ) ;
73+ _programName = Runtime . IsPython3
74+ ? UcsMarshaler . GetInstance ( "" ) . MarshalManagedToNative ( value )
75+ : Marshal . StringToHGlobalAnsi ( value ) ;
76+ Runtime . Py_SetProgramName ( _programName ) ;
77+ }
6878 }
6979
7080 public static string PythonHome
@@ -78,7 +88,14 @@ public static string PythonHome
7888
7989 return result ?? "" ;
8090 }
81- set { Runtime . Py_SetPythonHome ( value ) ; }
91+ set
92+ {
93+ Marshal . FreeHGlobal ( _pythonHome ) ;
94+ _pythonHome = Runtime . IsPython3
95+ ? UcsMarshaler . GetInstance ( "" ) . MarshalManagedToNative ( value )
96+ : Marshal . StringToHGlobalAnsi ( value ) ;
97+ Runtime . Py_SetPythonHome ( _pythonHome ) ;
98+ }
8299 }
83100
84101 public static string PythonPath
@@ -92,7 +109,14 @@ public static string PythonPath
92109
93110 return result ?? "" ;
94111 }
95- set { Runtime . Py_SetPath ( value ) ; }
112+ set
113+ {
114+ Marshal . FreeHGlobal ( _pythonPath ) ;
115+ _pythonPath = Runtime . IsPython3
116+ ? UcsMarshaler . GetInstance ( "" ) . MarshalManagedToNative ( value )
117+ : Marshal . StringToHGlobalAnsi ( value ) ;
118+ Runtime . Py_SetPath ( _pythonPath ) ;
119+ }
96120 }
97121
98122 public static string Version
@@ -284,6 +308,13 @@ public static void Shutdown()
284308 {
285309 if ( initialized )
286310 {
311+ Marshal . FreeHGlobal ( _pythonHome ) ;
312+ _pythonHome = IntPtr . Zero ;
313+ Marshal . FreeHGlobal ( _programName ) ;
314+ _programName = IntPtr . Zero ;
315+ Marshal . FreeHGlobal ( _pythonPath ) ;
316+ _pythonPath = IntPtr . Zero ;
317+
287318 Runtime . Shutdown ( ) ;
288319 initialized = false ;
289320 }
0 commit comments