我正在構建一個C#WebKit Web瀏覽器,該瀏覽器可以通過IronPython實現自動化以幫助進行質量保證測試。我將使用IronPython創建測試計劃,該計劃將運行許多瀏覽器方法,提供參數並評估結果。從IronPython調用C#方法
IronPython的大部分文檔說明了如何使用C#調用IronPython方法,但我已經想出瞭如何爲方法設置參數,以及如何檢索方法返回值,但不是來自同一方法。在下面的例子中你會注意到,我將一個參數傳遞給一個方法,該方法依次設置一個類成員變量,然後用另一種方法檢索該值。
任何人都可以提出一個更優雅的模式?
using System; using System.Windows.Forms; using IronPython.Hosting; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace PythonScripting.TestApp { public partial class Form1 : Form { private ScriptEngine m_engine = Python.CreateEngine(); private ScriptScope m_scope = null; //used to call funcs by Python that dont need to return vals delegate void VoidFunc(string val); public Form1() { InitializeComponent(); } private void doSomething() { MessageBox.Show("Something Done", "TestApp Result"); } private string _rslt = ""; private string getSomething() { return _rslt; } private void setSomething(string val) { _rslt = val; } private void Form1_Load(object sender, EventArgs e) { m_scope = m_engine.CreateScope(); Func<string> PyGetFunction = new Func<string>(getSomething); VoidFunc PySetFunction = new VoidFunc(setSomething); m_scope.SetVariable("txt", txtBoxTarget); m_scope.SetVariable("get_something", PyGetFunction); m_scope.SetVariable("set_something", PySetFunction); } private void button1_Click(object sender, EventArgs e) { string code = comboBox1.Text.Trim(); ScriptSource source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.SingleStatement); try { source.Execute(m_scope); Func<string> result = m_scope.GetVariable<Func<string>>("get_something"); MessageBox.Show("Result: " + result(), "TestApp Result"); } catch (Exception ue) { MessageBox.Show("Unrecognized Python Error\n\n" + ue.GetBaseException(), "Python Script Error"); } } } }
您定位的是哪個版本的框架?在這裏使用'dynamic'會使所有這些都變得微不足道。 –
謝謝傑夫,我是obv一個IronPython noob-我會研究這個... –
理解這段代碼真的幫助我,對任何感興趣的人:http://thinkingeek.com/2009/03/11/using-ironpython -to-extend-your-net-applications/ –