现在的位置: 首页 > 综合 > 正文

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

2013年02月03日 ⁄ 综合 ⁄ 共 1181字 ⁄ 字号 评论关闭

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

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

 

抱歉!评论已关闭.