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 に答える