Skip to content

Commit

Permalink
improved param marshaller
Browse files Browse the repository at this point in the history
  • Loading branch information
eirannejad committed Dec 16, 2023
1 parent 69aef49 commit 0ff0d65
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions src/runtime/McNeel.PythonEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -567,14 +567,36 @@ PyModule PrepareScope(string scopeName, string pythonFile)
#endregion

#region Marshalling
public object MarshInputList(IEnumerable enumerable)
public PyObject MarshInput(object value)
{
PyList pyList = new PyList();
switch (value)
{
case string str:
return MarshToPyObject(value);

case List<object> enumerable:
PyList pyList = new PyList();
foreach (object obj in enumerable)
pyList.Append(MarshInput(obj));
return pyList;

case Dictionary<string, object> dict:
PyDict pyDict = new PyDict();
foreach (KeyValuePair<string, object> pair in dict)
pyDict[pair.Key] = MarshInput(pair.Value);
return pyDict;

foreach (object obj in enumerable)
pyList.Append(PyObject.FromManagedObject(obj));
case PyObject pyObj:
return pyObj;
}

return pyList;
return MarshToPyObject(value);
}

PyObject MarshToPyObject(object value)
{
using var _value = Converter.ToPythonDetectType(value);
return PyObject.FromNullableReference(_value.Borrow());
}

public object MarshOutput(object value)
Expand All @@ -594,13 +616,13 @@ public object MarshOutput(object value)
}).ToDictionary(p => p.Key, p => p.Value);

case PyObject pyObj:
return MarshOutput(pyObj);
return MarshFromPyObject(pyObj);
}

return value;
}

object MarshOutput(PyObject pyObj)
object MarshFromPyObject(PyObject pyObj)
{
if (ManagedType.GetManagedObject(pyObj) is CLRObject co)
{
Expand All @@ -615,13 +637,13 @@ object MarshOutput(PyObject pyObj)
else if (Runtime.PyList_Check(pyObj))
{
var l = new PyList(pyObj);
return l.Select(i => MarshOutput(i)).ToList();
return l.Select(i => MarshFromPyObject(i)).ToList();
}

else if (Runtime.PyDict_Check(pyObj))
{
var d = new PyDict(pyObj);
return d.Keys().ToDictionary(k => MarshOutput(k), k => MarshOutput(d[k]));
return d.Keys().ToDictionary(k => MarshFromPyObject(k), k => MarshFromPyObject(d[k]));
}

else if (Runtime.PyString_CheckExact(pyObj))
Expand Down

0 comments on commit 0ff0d65

Please sign in to comment.