Skip to content

Commit e6eac73

Browse files
patstewtonyroberts
authored andcommitted
Add convenience functions to new Py class. Supports "using (Py.GIL()) {}" blocks to setup the python interpreter and take/release the GIL, and Py.kw("key1", value1, "key2", value2, ...) to add keyword arguments.
1 parent 25481af commit e6eac73

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

pythonnet/src/runtime/pythonengine.cs

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,10 +352,61 @@ public static PyObject RunString(string code) {
352352
}
353353
return new PyObject(result);
354354
}
355+
}
355356

357+
public static class Py
358+
{
359+
public static GILState GIL()
360+
{
361+
if (!PythonEngine.IsInitialized)
362+
PythonEngine.Initialize();
356363

364+
return new GILState();
365+
}
357366

358-
}
367+
public class GILState : IDisposable
368+
{
369+
private IntPtr state;
370+
internal GILState()
371+
{
372+
state = PythonEngine.AcquireLock();
373+
}
374+
public void Dispose()
375+
{
376+
PythonEngine.ReleaseLock(state);
377+
GC.SuppressFinalize(this);
378+
}
379+
~GILState()
380+
{
381+
Dispose();
382+
}
383+
}
359384

385+
public class KeywordArguments : PyDict { }
386+
387+
public static KeywordArguments kw(params object[] kv)
388+
{
389+
var dict = new KeywordArguments();
390+
if (kv.Length % 2 != 0)
391+
throw new ArgumentException("Must have an equal number of keys and values");
392+
for (int i = 0; i < kv.Length; i += 2)
393+
{
394+
IntPtr value;
395+
if (kv[i + 1] is PyObject)
396+
value = ((PyObject)kv[i + 1]).Handle;
397+
else
398+
value = Converter.ToPython(kv[i + 1], kv[i + 1].GetType());
399+
if (Runtime.PyDict_SetItemString(dict.Handle, (string)kv[i], value) != 0)
400+
throw new ArgumentException(string.Format("Cannot add key '{0}' to dictionary.", (string)kv[i]));
401+
if (!(kv[i + 1] is PyObject))
402+
Runtime.Decref(value);
403+
}
404+
return dict;
405+
}
360406

407+
public static PyObject Import(string name)
408+
{
409+
return PythonEngine.ImportModule(name);
410+
}
411+
}
361412
}

0 commit comments

Comments
 (0)