I want to create an instance of an IronPython class from C#, but my current attempts all seem to have failed.
This is my current code:
ConstructorInfo[] ci = type.GetConstructors();
foreach (ConstructorInfo t in from t in ci
where t.GetParameters().Length == 1
select t)
{
PythonType pytype = DynamicHelpers.GetPythonTypeFromType(type);
object[] consparams = new object[1];
consparams[0] = pytype;
_objects[type] = t.Invoke(consparams);
pytype.__init__(_objects[type]);
break;
}
I am able to get the created instance of the object from calling t.Invoke(consparams), but the __init__
method doesn't seem to be called, and thus all the properties that I set from my Python script aren't used. Even with the explicit pytype.__init__
call, the constructed object still doesn't seem to be initialised.
Using ScriptEngine.Operations.CreateInstance doesn't seem to work, either.
I'm using .NET 4.0 with IronPython 2.6 for .NET 4.0.
EDIT: Small clarification on how I'm intending to do this:
In C#, I have a class as follows:
public static class Foo
{
public static object Instantiate(Type type)
{
// do the instantiation here
}
}
And in Python, the following code:
class MyClass(object):
def __init__(self):
print "this should be called"
Foo.Instantiate(MyClass)
The __init__
method never seems to be called.