Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
fixed PyObject.As<object> returning PyObject
  • Loading branch information
lostmsu committed Sep 5, 2021
commit 14a10d5342b400ceff334d9f2d720595eb8f69d9
25 changes: 25 additions & 0 deletions src/embed_tests/Codecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,31 @@ from datetime import datetime

public static void AcceptsDateTime(DateTime v) {}

[Test]
public void As_Object_AffectedByDecoders()
{
var everythingElseToSelf = new EverythingElseToSelfDecoder();
PyObjectConversions.RegisterDecoder(everythingElseToSelf);

var pyObj = PythonEngine.Eval("iter");
var decoded = pyObj.As<object>();
Assert.AreSame(everythingElseToSelf, decoded);
}

public class EverythingElseToSelfDecoder : IPyObjectDecoder
{
public bool CanDecode(PyObject objectType, Type targetType)
{
return targetType.IsAssignableFrom(typeof(EverythingElseToSelfDecoder));
}

public bool TryDecode<T>(PyObject pyObj, out T value)
{
value = (T)(object)this;
return true;
}
}

class ValueErrorWrapper : Exception
{
public ValueErrorWrapper(string message) : base(message) { }
Expand Down
14 changes: 2 additions & 12 deletions src/runtime/pyobject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,20 +163,10 @@ public object AsManagedObject(Type t)
}

/// <summary>
/// As Method
/// </summary>
/// <remarks>
/// Return a managed object of the given type, based on the
/// value of the Python object.
/// </remarks>
public T As<T>()
{
if (typeof(T) == typeof(PyObject) || typeof(T) == typeof(object))
{
return (T)(this as object);
}
return (T)AsManagedObject(typeof(T));
}
/// </summary>
public T As<T>() => (T)this.AsManagedObject(typeof(T));

internal bool IsDisposed => obj == IntPtr.Zero;

Expand Down