上兩篇IronPython腳本的文章介紹了與C#緊密結合的示例,這裡還将提供一個與C#結合更緊密的示例,直接調用C#編寫的DLL。
我們還是沿用了上篇文章的代碼(其實這裡可以直接使用IronPython調試器進行聯調了,沒有必要再嵌入到C#了)
注意:scriptEngine.AddToPath(Application.StartupPath); 這句代碼比較關鍵,設定dll檔案所在的目錄。
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.AddToPath(Application.StartupPath);
scriptEngine.Execute(textBox1.Text);
}
}
開始編寫可供IronPython腳本調用的DLL,我們編寫了兩個類,一個提供靜态函數通路,另一個提供屬性和普通函數通路,以差別在IronPython腳本不同調用的方式。代碼如下:
namespace IronPython_TestDll
public class TestDll
public static int Add(int x, int y)
return x + y;
public class TestDll1
private int aaa = 11;
public int AAA
get { return aaa; }
set { aaa = value; }
public void ShowAAA()
global::System.Windows.Forms.MessageBox.Show(aaa.ToString());
下面再讓我們看看IronPython腳本中的代碼吧:
import clr
clr.AddReferenceByPartialName("System.Windows.Forms")
clr.AddReferenceByPartialName("System.Drawing")
from System.Windows.Forms import *
from System.Drawing import *
clr.AddReferenceToFile("IronPython_TestDll.dll")
from IronPython_TestDll import *
a=12
b=6
c=TestDll.Add(a,b)
MessageBox.Show(c.ToString())
td=TestDll1()
td.AAA=100
td.ShowAAA()
比較關鍵的是這兩句:
clr.AddReferenceToFile("TronPython_TestDll.dll") -- 加載DLL檔案
from TronPython_TestDll import * -- 導入命名空間
靜态方法可以直接調用,普通方法需要先定義類,再通路(和通路IronPython
自己本身的類沒有任何差別)。
運作結果如下:
現在你是否對IronPython充滿期待和興趣了吧,動起手來,感受它的強大!