从C创建IronPython类的实例#

2024-10-01 13:45:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从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似乎也不管用。在

我使用.NET4.0和IronPython2.6 for.NET4.0。在

编辑:关于我打算如何做的小说明:

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

^{pr2}$

在Python中,以下代码:

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

Foo.Instantiate(MyClass)

似乎从未调用__init__方法。在


Tags: 对象实例方法代码inciobjectsobject
3条回答

我想我用.NET Type类解决了我自己的问题,似乎已经放弃了Python类型信息。在

IronPython.Runtime.Types.PythonType替换它效果很好。在

这段代码适用于IronPython2.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
    }

根据澄清问题编辑

^{pr2}$

看起来您正在寻找给this SO question的答案。在

相关问题 更多 >