Skip to content

Commit 2995a46

Browse files
committed
Keep reference to PythonHome and dealloc at end
1 parent 964af38 commit 2995a46

File tree

2 files changed

+28
-6
lines changed

2 files changed

+28
-6
lines changed

src/embed_tests/TestPythonEngineProperties.cs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,27 @@ public static void GetPythonHomeDefault()
107107
}
108108

109109
[Test]
110-
public void TestSetHome()
110+
public void SetPythonHome()
111111
{
112-
string homePath = @"C:\Python27\";
113-
PythonEngine.PythonHome = homePath;
112+
var pythonHome = "/dummypath/";
113+
114+
PythonEngine.PythonHome = pythonHome;
115+
PythonEngine.Initialize();
116+
117+
Assert.AreEqual(pythonHome, PythonEngine.PythonHome);
118+
PythonEngine.Shutdown();
119+
}
120+
121+
[Test]
122+
public void SetPythonHomeTwice()
123+
{
124+
var pythonHome = "/dummypath/";
125+
126+
PythonEngine.PythonHome = "/dummypath2/";
127+
PythonEngine.PythonHome = pythonHome;
114128
PythonEngine.Initialize();
115-
Assert.AreEqual(PythonEngine.PythonHome, homePath);
129+
130+
Assert.AreEqual(pythonHome, PythonEngine.PythonHome);
116131
PythonEngine.Shutdown();
117132
}
118133
}

src/runtime/pythonengine.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ public class PythonEngine : IDisposable
1414
{
1515
private static DelegateManager delegateManager;
1616
private static bool initialized;
17+
private static IntPtr _pythonHome = IntPtr.Zero;
1718

1819
public PythonEngine()
1920
{
@@ -80,8 +81,12 @@ public static string PythonHome
8081
}
8182
set
8283
{
83-
IntPtr pythonHome = Marshal.StringToHGlobalAnsi(value);
84-
Runtime.Py_SetPythonHome(pythonHome);
84+
if (_pythonHome != IntPtr.Zero)
85+
{
86+
Marshal.FreeHGlobal(_pythonHome);
87+
}
88+
_pythonHome = Marshal.StringToHGlobalAnsi(value);
89+
Runtime.Py_SetPythonHome(_pythonHome);
8590
}
8691
}
8792

@@ -288,6 +293,8 @@ public static void Shutdown()
288293
{
289294
if (initialized)
290295
{
296+
Marshal.FreeHGlobal(_pythonHome);
297+
_pythonHome = IntPtr.Zero;
291298
Runtime.Shutdown();
292299
initialized = false;
293300
}

0 commit comments

Comments
 (0)