Skip to content
Closed
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
Fixed issue with protected constructors and classes with no constructor
  • Loading branch information
rmadsen-ks committed Oct 31, 2022
commit 65c2c008834bc4380aad322fb4a72ef7c5a68752
14 changes: 10 additions & 4 deletions src/runtime/Types/ClassDerived.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,17 @@ internal static Type CreateDerivedType(string name,
FieldAttributes.Private);

// override any constructors
ConstructorInfo[] constructors = baseClass.GetConstructors();
ConstructorInfo[] constructors = baseClass.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (ConstructorInfo ctor in constructors)
{
AddConstructor(ctor, baseType, typeBuilder);
}

if (constructors.Length == 0)
{
AddConstructor(null, baseType, typeBuilder);
}

// Override any properties explicitly overridden in python
var pyProperties = new HashSet<string>();
if (py_dict != null && Runtime.PyDict_Check(py_dict))
Expand Down Expand Up @@ -303,7 +308,7 @@ internal static Type CreateDerivedType(string name,
/// <param name="typeBuilder">TypeBuilder for the new type the ctor is to be added to</param>
private static void AddConstructor(ConstructorInfo ctor, Type baseType, TypeBuilder typeBuilder)
{
ParameterInfo[] parameters = ctor.GetParameters();
ParameterInfo[] parameters = ctor?.GetParameters() ?? Array.Empty<ParameterInfo>();
Type[] parameterTypes = (from param in parameters select param.ParameterType).ToArray();

// create a method for calling the original constructor
Expand All @@ -322,14 +327,15 @@ private static void AddConstructor(ConstructorInfo ctor, Type baseType, TypeBuil
{
il.Emit(OpCodes.Ldarg, i + 1);
}
il.Emit(OpCodes.Call, ctor);
if(ctor != null)
il.Emit(OpCodes.Call, ctor);
il.Emit(OpCodes.Ret);

// override the original method with a new one that dispatches to python
ConstructorBuilder cb = typeBuilder.DefineConstructor(MethodAttributes.Public |
MethodAttributes.ReuseSlot |
MethodAttributes.HideBySig,
ctor.CallingConvention,
ctor?.CallingConvention ?? CallingConventions.Any,
parameterTypes);
il = cb.GetILGenerator();
il.DeclareLocal(typeof(object[]));
Expand Down