C#與python結合編程
形式:用C#寫界面和事件觸發(fā),調用python腳本進行邏輯和數(shù)據(jù)處理。 好處:編寫好界面和事件觸發(fā)之后誊册,可以動態(tài)改動py腳本窍奋,不需要重新編譯程序荐健。 缺點:使用的電腦需要裝有python,同時程序需附帶多個ironpython的dll琳袄。??
方法:?
1江场、安裝ironpython
?2、新建C#項目窖逗。添加引用:IronPython.dll址否,Microsoft.Dynamic.dll,Microsoft.Scripting.dll?
3碎紊、在C#文件添加python的調用佑附。?
//聲明并定義調用python的類?
ScriptEngine engine;
?ScriptScope scope;?
object myInstance;?
engine = Python.CreateEngine();?
scope = engine.CreateScope();
?var code = engine.CreateScriptSourceFromString("XXXXX");
//通過string文本調用py語句樊诺,也可以調用fromfiles函數(shù)來調用py腳本?
code.Execute(scope);
//執(zhí)行上述py代碼?
var myClass = scope.GetVariable>("Control");?
//把py腳本中的類提到C#中,或者是調用py腳本中的類或者變量?
myInstance = myClass("hello world", textBox1.Text);
//實例化該類音同,并能調用構造函數(shù)進行初始化?
//把C#的變量傳入到py中?
engine.Operations.SetMember(myInstance, "listBox1", listBox1);?
engine.Operations.SetMember(myInstance, "treeView1", treeView1);?
engine.Operations.SetMember(myInstance, "richTextBox1", richTextBox1);
?//調用py腳本中的類成員函數(shù)?
engine.Operations.GetMember>(myInstance, "GetTree")(textBox1.Text);?
4词爬、在python文件添加C#類?
#引入ironpython庫和C#庫?
#添加python庫?
import clr,sys?
clr.AddReference('IronPython')?
clr.AddReference('System.Windows.Forms')?
clr.AddReference('System.Drawing')?
sys.path.append("C:\Python27\DLLs")?
sys.path.append("C:\Python27\Lib")?
#把C#的控件類提出來,也可以直接import权均,但是調用這些空間的時候就要把調用寫全顿膨,例如
System.Windows.Forms.TreeNode?
from?System.Windows.Forms import TreeNode?
from?System.Windows.Forms import ListBox?
from?System.Windows.Forms
import TreeView from System.Windows.Forms
import TextBox from System.Windows.Forms?
import RichTextBox from System.Drawing import Color?
把C#空間類實例化 listBox1 = ListBox()
出處(http://www.wpf123.com/)