Creating instances of IronPython classes from C #

I want to create an instance of the IronPython class from C #, but my current attempts do not seem to work.

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 can get the instantiated object from the call to t.Invoke (consparams), but the __init__ method does not seem to be called, and therefore, all the properties that I set from my Python script are not used. Even with an explicit call to pytype.__init__ constructed object is still not initialized.

Using ScriptEngine.Operations.CreateInstance also does not work.

I am using .NET 4.0 with IronPython 2.6 for .NET 4.0.

EDIT : A little clarification on how I intend 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 is never called.

+4
source share
3 answers

This code works with IronPython 2.6.1

  static void Main(string[] args) { const string script = @" class A(object) : def __init__(self) : self.a = 100 class B(object) : def __init__(self, a, v) : self.a = a self.v = v def run(self) : return self.aa + self.v "; var engine = Python.CreateEngine(); var scope = engine.CreateScope(); engine.Execute(script, scope); var typeA = scope.GetVariable("A"); var typeB = scope.GetVariable("B"); var a = engine.Operations.CreateInstance(typeA); var b = engine.Operations.CreateInstance(typeB, a, 20); Console.WriteLine(b.run()); // 120 } 

EDITED according to the specified question

  class Program { static void Main(string[] args) { var engine = Python.CreateEngine(); var scriptScope = engine.CreateScope(); var foo = new Foo(engine); scriptScope.SetVariable("Foo", foo); const string script = @" class MyClass(object): def __init__(self): print ""this should be called"" Foo.Create(MyClass) "; var v = engine.Execute(script, scriptScope); } } public class Foo { private readonly ScriptEngine engine; public Foo(ScriptEngine engine) { this.engine = engine; } public object Create(object t) { return engine.Operations.CreateInstance(t); } } 
+11
source

I think I solved my own question - using the .NET Type class seems to have dropped Python type information.

Replacing it with IronPython.Runtime.Types.PythonType works quite well.

+2
source

It looks like you are looking for the answer to this SO question .

+1
source

All Articles