C#嵌入IronPython脚本示例(hello world)

<meta content="MSHTML 6.00.2900.3199" name="GENERATOR"> <style></style>2007年06月01日 15:08:00

随着项目的逐渐收尾, 对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!"

怎么样,是不是很简单?!



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1634226


你可能感兴趣的:(C++,c,windows,脚本,C#)