Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 56ca4c9

Browse files
committed
a test to ensure it is possible to override argument conversion for inherited methods using an attribute on a derived class
1 parent 6cd7bd4 commit 56ca4c9

File tree

1 file changed

+34
-5
lines changed

1 file changed

+34
-5
lines changed

src/embed_tests/TestCustomArgMarshal.cs

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,27 @@ public void CustomArgMarshaller()
2828
}
2929
Assert.AreEqual(expected: 42, actual: obj.LastArgument);
3030
}
31+
32+
[Test]
33+
public void MarshallerOverride() {
34+
var obj = new DerivedMarshaling();
35+
using (Py.GIL()) {
36+
dynamic callWithInt = PythonEngine.Eval("lambda o: o.CallWithInt({ 'value': 42 })");
37+
callWithInt(obj.ToPython());
38+
}
39+
Assert.AreEqual(expected: 42, actual: obj.LastArgument);
40+
}
3141
}
3242

33-
[PyArgConverter(typeof(CustomArgConverter))]
34-
class CustomArgMarshaling {
35-
public object LastArgument { get; private set; }
36-
public void CallWithInt(int value) => this.LastArgument = value;
37-
}
43+
[PyArgConverter(typeof(CustomArgConverter))]
44+
class CustomArgMarshaling {
45+
public object LastArgument { get; protected set; }
46+
public virtual void CallWithInt(int value) => this.LastArgument = value;
47+
}
48+
49+
// this should override original custom marshaling behavior
50+
[PyArgConverter(typeof(CustomArgConverter2))]
51+
class DerivedMarshaling: CustomArgMarshaling { }
3852

3953
class CustomArgConverter : DefaultPyArgumentConverter {
4054
public override bool TryConvertArgument(IntPtr pyarg, Type parameterType, bool needsResolution,
@@ -52,4 +66,19 @@ public override bool TryConvertArgument(IntPtr pyarg, Type parameterType, bool n
5266
return true;
5367
}
5468
}
69+
70+
class CustomArgConverter2 : DefaultPyArgumentConverter {
71+
public override bool TryConvertArgument(IntPtr pyarg, Type parameterType, bool needsResolution,
72+
out object arg, out bool isOut) {
73+
if (parameterType != typeof(int))
74+
return base.TryConvertArgument(pyarg, parameterType, needsResolution, out arg, out isOut);
75+
bool isPyObject = base.TryConvertArgument(pyarg, typeof(PyObject), needsResolution,
76+
out arg, out isOut);
77+
if (!isPyObject) return false;
78+
var dict = new PyDict((PyObject)arg);
79+
int number = (dynamic)dict["value"];
80+
arg = number;
81+
return true;
82+
}
83+
}
5584
}

0 commit comments

Comments
 (0)