-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLazyPyObject.cs
More file actions
110 lines (84 loc) · 2.72 KB
/
LazyPyObject.cs
File metadata and controls
110 lines (84 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using Python.Runtime;
namespace PythonContainer;
public class LazyPyObject
{
private readonly string _mainImport;
private readonly Dictionary<string, PyObject> _imports = [];
private readonly Dictionary<string, PyObject> _attributes = [];
private PyObject MainImport => GetOrAddCachedImport(_mainImport);
public PyObject PyObject => MainImport;
public dynamic DynamicObject => MainImport;
public LazyPyObject(string @namespace)
{
_mainImport = @namespace;
}
public PyObject GetImport(string @namespace)
=> GetOrAddCachedImport(@namespace);
public T GetAttribute<T>(string attribute)
=> GetOrAddCachedAttribute(attribute).As<T>();
public PyObject GetAttribute(string attribute)
=> GetOrAddCachedAttribute(attribute);
public void InvokeFunction(string attribute, params object[] args)
{
var pyArgs = ConvertToPyObjects(args);
var attr = GetOrAddCachedAttribute(attribute);
attr.Invoke(pyArgs.ToArray());
CleanUp(pyArgs);
}
public T InvokeFunction<T>(string attribute, params object[] args)
{
var pyArgs = ConvertToPyObjects(args);
var attr = GetOrAddCachedAttribute(attribute);
var result = attr.Invoke(pyArgs.ToArray());
CleanUp(pyArgs);
return result.As<T>();
}
protected static IEnumerable<PyObject> ConvertToPyObjects(params object[] args)
{
foreach (var arg in args)
{
if (arg is PyObject pyObj)
yield return pyObj;
else if(arg is LazyPyObject lazyObj)
yield return lazyObj.PyObject;
else
yield return PyObject.FromManagedObject(arg);
}
}
protected static void CleanUp(PyObject[] args)
{
foreach (var arg in args)
arg.Dispose();
}
protected static void CleanUp(IEnumerable<PyObject> args)
{
foreach (var arg in args)
arg.Dispose();
}
protected PyObject GetOrAddCachedAttribute(string attribute)
{
if (!_attributes.TryGetValue(attribute, out var obj))
{
obj = MainImport.GetAttr(attribute);
_attributes[attribute] = obj;
}
return obj;
}
protected PyObject GetOrAddCachedImport(string import)
{
if (!_imports.TryGetValue(import, out var obj))
{
obj = Py.Import(import);
_imports[import] = obj;
}
return obj;
}
public void Dispose()
{
foreach (var property in _attributes)
property.Value.Dispose();
foreach (var property in _imports)
property.Value.Dispose();
GC.SuppressFinalize(this);
}
}