4

これは、私が理解できない単純なエラーがあるようです。C# WPF アプリケーションで IronPython を使用していますが、カスタム C# クラスから関数を実行しようとすると、次のエラーが発生します: AttributeError: 'MyScriptingFunctions' object has no attribute 'Procedure'.

私が実行している python スクリプトは非常に単純で、2 行あります。1 行目は問題なく実行されますが、2 行目でエラーが発生します。

    txt.Text = "some text"
    MyFunc.Procedure(5)

MyScriptingFunctions.cs:

class MyScriptingFunctions
{
    public MyScriptingFunctions() {}

    public void Procedure(int num)
    {
        Console.WriteLine("Executing procedure " + num); 
    }
}

IronPython エンジンをセットアップする方法は次のとおりです。

     private void btnRunScript_Click(object sender, RoutedEventArgs e)
     {
        MyScriptingFunctions scriptFuncs = new MyScriptingFunctions();
        ScriptEngine engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();

        ScriptRuntime runtime = engine.Runtime;
        runtime.LoadAssembly(typeof(String).Assembly);
        runtime.LoadAssembly(typeof(Uri).Assembly);

        //Set Variable for the python script to use
        scope.SetVariable("txt", fullReadResultsTextBox);
        scope.SetVariable("MyFunc", scriptFuncs);
        string code = this.scriptTextBox.Text;
        try
        {
            ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
            source.Execute(scope);
        }
        catch (Exception ex)
        {
            ExceptionOperations eo;
            eo = engine.GetService<ExceptionOperations>();
            string error = eo.FormatException(ex);

            MessageBox.Show(error, "There was an Error");
            return;
        }

    }

単純に 2 つの変数を設定しています。txtどちらが typeSystem.Windows.Controls.TextBoxで、MyFuncどちらがカスタム クラスのオブジェクトですMyScriptingFunctions

何が間違っているのですか? また、python スクリプトが TextBox メソッドを正しく実行し、カスタム クラスのメソッドを実行しないのはなぜですか?

4

1 に答える 1

7

問題である可能性がある、または単にコピーアンドペーストエラーである可能性があると私が思う唯一のことは、MyScriptingFunctionsin not public. クラスをインポートしようとしているのではなく、インスタンスを渡しているため、これは問題にはなりませんが、試してみる価値はあります。それ以外の場合は、すべて正常に見えます。

于 2013-06-19T21:45:47.307 に答える