Skip to content

Prevent stack overflow when an encoder is registered from Python #1429

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

Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ One must now either use enum members (e.g. `MyEnum.Option`), or use enum constru
- Sign Runtime DLL with a strong name
- Implement loading through `clr_loader` instead of the included `ClrModule`, enables
support for .NET Core
- BREAKING: custom encoders are no longer called for instances of `System.Type`

### Fixed

Expand Down
26 changes: 26 additions & 0 deletions src/embed_tests/Codecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,32 @@ public void IterableDecoderTest()
Assert.DoesNotThrow(() => { codec.TryDecode(pyList, out intEnumerable); });
CollectionAssert.AreEqual(intEnumerable, new List<object> { 1, 2, 3 });
}

// regression for https://github.com/pythonnet/pythonnet/issues/1427
[Ignore("https://github.com/pythonnet/pythonnet/issues/1256")]
[Test]
public void PythonRegisteredDecoder_NoStackOverflowOnSystemType()
{
const string PyCode = @"
import clr
import System
from Python.Runtime import PyObjectConversions
from Python.Runtime.Codecs import RawProxyEncoder


class ListAsRawEncoder(RawProxyEncoder):
__namespace__ = 'Dummy'
def CanEncode(self, clr_type):
return clr_type.Name == 'IList`1' and clr_type.Namespace == 'System.Collections.Generic'


list_encoder = ListAsRawEncoder()
PyObjectConversions.RegisterEncoder(list_encoder)

system_type = list_encoder.GetType()";

PythonEngine.Exec(PyCode);
}
}

/// <summary>
Expand Down
7 changes: 5 additions & 2 deletions src/runtime/converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,11 @@ internal static IntPtr ToPython(object value, Type type)
return result;
}

if (Type.GetTypeCode(type) == TypeCode.Object && value.GetType() != typeof(object)
|| type.IsEnum) {
if (Type.GetTypeCode(type) == TypeCode.Object
&& value.GetType() != typeof(object)
&& value is not Type
|| type.IsEnum
) {
var encoded = PyObjectConversions.TryEncode(value, type);
if (encoded != null) {
result = encoded.Handle;
Expand Down