Skip to content

Add codecs for functions #1080

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
encoder
  • Loading branch information
koubaa committed Mar 6, 2020
commit 9ca2c057c949c37ace4c55b6a67bc22909dcc271
71 changes: 46 additions & 25 deletions src/embed_tests/Codecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,42 +99,63 @@ static void TupleRoundtripGeneric<T, TTuple>()
}

[Test]
public void Function()
public void FunctionAction()
{

FunctionCodec.Register();
var codec = FunctionCodec.Instance;
var locals = new PyDict();

//non-callables can't be decoded into Action
Assert.IsFalse(codec.CanDecode(locals, typeof(Action)));
//decoding - python functions to C# actions
{
PyInt x = new PyInt(1);
PyDict y = new PyDict();
//non-callables can't be decoded into Action
Assert.IsFalse(codec.CanDecode(x, typeof(Action)));
Assert.IsFalse(codec.CanDecode(y, typeof(Action)));

PythonEngine.Exec(@"
var locals = new PyDict();
PythonEngine.Exec(@"
def foo():
return 1
def bar(a):
return 2
", null, locals.Handle);

//foo
var fooFunc = locals.GetItem("foo");
Assert.IsFalse(codec.CanDecode(fooFunc, typeof(bool)));
Assert.IsFalse(codec.CanDecode(fooFunc, typeof(Action<object[]>)));
Assert.IsTrue(codec.CanDecode(fooFunc, typeof(Action)));

Action fooAction;
Assert.IsTrue(codec.TryDecode(fooFunc, out fooAction));
Assert.DoesNotThrow(() => fooAction());

//bar
var barFunc = locals.GetItem("bar");
Assert.IsFalse(codec.CanDecode(barFunc, typeof(bool)));
Assert.IsFalse(codec.CanDecode(barFunc, typeof(Action)));
Assert.IsTrue(codec.CanDecode(barFunc, typeof(Action<object[]>)));

Action<object[]> barAction;
Assert.IsTrue(codec.TryDecode(barFunc, out barAction));
Assert.DoesNotThrow(() => barAction(new[]{ (object)true}));
//foo, the function with no arguments
var fooFunc = locals.GetItem("foo");
Assert.IsFalse(codec.CanDecode(fooFunc, typeof(bool)));
Assert.IsFalse(codec.CanDecode(fooFunc, typeof(Action<object[]>)));
Assert.IsTrue(codec.CanDecode(fooFunc, typeof(Action)));

Action fooAction;
Assert.IsTrue(codec.TryDecode(fooFunc, out fooAction));
Assert.DoesNotThrow(() => fooAction());

//bar, the function with an argument
var barFunc = locals.GetItem("bar");
Assert.IsFalse(codec.CanDecode(barFunc, typeof(bool)));
Assert.IsFalse(codec.CanDecode(barFunc, typeof(Action)));
Assert.IsTrue(codec.CanDecode(barFunc, typeof(Action<object[]>)));

Action<object[]> barAction;
Assert.IsTrue(codec.TryDecode(barFunc, out barAction));
Assert.DoesNotThrow(() => barAction(new[] { (object)true }));
}

//encoding, C# actions to python functions
{
//can't decode non-actions
Assert.IsFalse(codec.CanEncode(typeof(int)));
Assert.IsFalse(codec.CanEncode(typeof(Dictionary<string, int>)));

Action foo = () => { };
Assert.IsTrue(codec.CanEncode(foo.GetType()));

Assert.DoesNotThrow(() => { codec.TryEncode(foo); });

Action<object[]> bar = (object[] args) => { var z = args.Length; };
Assert.IsTrue(codec.CanEncode(bar.GetType()));
Assert.DoesNotThrow(() => { codec.TryEncode(bar); });
}
}
}
}
152 changes: 150 additions & 2 deletions src/runtime/Codecs/FunctionCodec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,123 @@

namespace Python.Runtime.Codecs
{
//like MethodWrapper but not static, so we can throw some state into it.
internal class MethodWrapper2
{
public IntPtr mdef;
public IntPtr ptr;
private bool _disposed = false;
private ThunkInfo _thunk;

public MethodWrapper2(object instance, string name, string funcType = null)
{
// Turn the managed method into a function pointer
var type = instance.GetType();
_thunk = GetThunk(instance, type.GetMethod(name), funcType);

// Allocate and initialize a PyMethodDef structure to represent
// the managed method, then create a PyCFunction.

mdef = Runtime.PyMem_Malloc(4 * IntPtr.Size);
TypeManager.WriteMethodDef(mdef, name, _thunk.Address, 0x0003);
ptr = Runtime.PyCFunction_NewEx(mdef, IntPtr.Zero, IntPtr.Zero);
}

internal static ThunkInfo GetThunk(object instance, System.Reflection.MethodInfo method, string funcType = null)
{
Type dt;
if (funcType != null)
dt = typeof(Interop).GetNestedType(funcType) as Type;
else
dt = Interop.GetPrototype(method.Name);

if (dt == null)
{
return ThunkInfo.Empty;
}
Delegate d = Delegate.CreateDelegate(dt, instance, method);
var info = new ThunkInfo(d);
return info;
}

/*public IntPtr Call(IntPtr args, IntPtr kw)
{
return Runtime.PyCFunction_Call(ptr, args, kw);
}*/

public void Release()
{
if (_disposed)
{
return;
}
_disposed = true;
bool freeDef = Runtime.Refcount(ptr) == 1;
Runtime.XDecref(ptr);
if (freeDef && mdef != IntPtr.Zero)
{
Runtime.PyMem_Free(mdef);
mdef = IntPtr.Zero;
}
}
}

//class which wraps a thing
internal class ActionWrapper
{
Action<object[]> _action = null;
internal ActionWrapper(Action action)
{
_action = (object[] args) => { action(); };
}

internal ActionWrapper(Action<object[]> action)
{
_action = action;
}

public virtual IntPtr RunAction(IntPtr self, IntPtr args)
{
var numArgs = Runtime.PyTuple_Size(args);
{
object[] managedArgs = null;
if (numArgs > 0)
{
managedArgs = new object[numArgs];
for (int idx = 0; idx < numArgs; ++idx)
{
IntPtr item = Runtime.PyTuple_GetItem(args, idx);
object result;
//this will cause an exception to be raised if there is a failure,
// so we can safely return IntPtr.Zero
bool setError = true;
if (!Converter.ToManaged(item, typeof(object), out result, setError))
return IntPtr.Zero;

managedArgs[idx] = result;
}
}

//get the args out, convert them each to C# one by one.

//call the action with the C# args
try
{
_action(managedArgs);
}
catch
{
Exceptions.SetError(Exceptions.TypeError, "Action threw an exception");
return IntPtr.Zero;
}
}

return Runtime.PyNone;
}
}

//converts python functions to C# actions
class FunctionCodec : IPyObjectDecoder
class FunctionCodec : IPyObjectDecoder, IPyObjectEncoder
{
private static int GetNumArgs(PyObject pyCallable)
{
Expand All @@ -28,9 +143,19 @@ private static int GetNumArgs(Type targetType)
return args.Length;
}

private static bool IsUnaryAction(Type targetType)
{
return targetType == typeof(Action);
}

private static bool IsVariadicObjectAction(Type targetType)
{
return targetType == typeof(Action<object[]>);
}

private static bool IsAction(Type targetType)
{
return targetType.FullName.StartsWith("System.Action");
return IsUnaryAction(targetType) || IsVariadicObjectAction(targetType);
}

private static bool IsCallable(Type targetType)
Expand Down Expand Up @@ -113,6 +238,29 @@ public bool TryDecode<T>(PyObject pyObj, out T value)
public static void Register()
{
PyObjectConversions.RegisterDecoder(Instance);
PyObjectConversions.RegisterEncoder(Instance);
}

public bool CanEncode(Type type)
{
return IsCallable(type);
}

public PyObject TryEncode(object value)
{
if (value == null) return null;

var targetType = value.GetType();
ActionWrapper wrapper = null;
if (IsUnaryAction(targetType))
wrapper = new ActionWrapper(value as Action);
else if (IsVariadicObjectAction(targetType))
wrapper = new ActionWrapper(value as Action<object[]>);

var methodWrapper = new MethodWrapper2(wrapper, "RunAction", "BinaryFunc");

//TODO - lifetime??
return new PyObject(methodWrapper.ptr);
}
}
}