随着項目的逐漸收尾, 對IronPython腳本也越來越熟悉,這裡為IronPython腳本感興趣但不入門的朋友寫幾篇使用心得,這是第一個:最簡單的hello world程式。
首先,我們必須有一個IronPython腳本引擎庫(IronPython.dll),我用的版本是V1.0,你可以在網上直接下到相關源碼,編譯後即生成IronPython.dll。
建立一個C#桌面程式,引用該庫後,我們便開始編寫第一個程式。
下面是C#中的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using IronPython.Hosting;
namespace TestIronPython
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
PythonEngine scriptEngine = new PythonEngine();
scriptEngine.Execute(textBox1.Text);
}
}
代碼很簡單,聲明了一個scriptEngine 執行個體,直接用Execute執行代碼即可。下面看看py的代碼該怎麼寫:
import clr
clr.AddReferenceByPartialName("System.Windows.Forms")
clr.AddReferenceByPartialName("System.Drawing")
from System.Windows.Forms import *
from System.Drawing import *
MessageBox.Show("Hello World!")
第一句代碼很重要,導入.net clr,用clr的AddReferenceByPartialName方法加載我們熟悉的System.Windows.Forms和System.Drawing庫,最後可以直接執行.net中的MessageBox方法。
運作後,直接單擊button1,即可彈出一個對話框"Hello World!"
怎麼樣,是不是很簡單?!