6

我想从 C# 创建 IronPython 类的实例,但我目前的尝试似乎都失败了。

这是我当前的代码:

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;
}

我可以通过调用 t.Invoke(consparams) 来获取创建的对象实例,但__init__似乎没有调用该方法,因此我从 Python 脚本中设置的所有属性都没有使用。即使使用显式pytype.__init__调用,构造的对象似乎仍然没有被初始化。

使用 ScriptEngine.Operations.CreateInstance 似乎也不起作用。

我将 .NET 4.0 与 IronPython 2.6 一起用于 .NET 4.0。

编辑:关于我打算如何做到这一点的小说明:

在 C# 中,我有一个类如下:

public static class Foo
{
    public static object Instantiate(Type type)
    {
        // do the instantiation here
    }
}

在 Python 中,以下代码:

class MyClass(object):
    def __init__(self):
        print "this should be called"

Foo.Instantiate(MyClass)

__init__方法似乎从未被调用。

4

3 回答 3

10

此代码适用于 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.a.a + 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
    }

根据澄清的问题编辑

    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);
    }
}
于 2010-08-04T07:09:31.423 回答
2

我想我解决了自己的问题——使用 .NETType类似乎丢弃了 Python 类型信息。

将其替换为IronPython.Runtime.Types.PythonType效果很好。

于 2010-08-04T07:47:43.930 回答
0

看起来您正在寻找这个 SO question的答案。

于 2010-08-04T05:10:06.923 回答