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

随着项目的逐渐收尾, 对IronPython脚本也越来越熟悉,这里为IronPython脚本感兴趣但不入门的朋友写几篇使用心得,这是第一个:最简单的hello world程序。

        首先,我们必须有一个IronPython脚本引擎库(IronPython.dll),我用的版本是V1.0,你可以在网上直接下到相关源码,编译后即生成IronPython.dll。

        新建一个C#桌面程序,引用该库后,我们便开始编写第一个程序。

        下面是C#中的代码:

  
  
  
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using IronPython.Hosting;  
  9.  
  10. namespace TestIronPython  
  11. {  
  12.      
  13.     public partial class Form1 : Form  
  14.     {  
  15.  
  16.        public Form1()  
  17.         {  
  18.             InitializeComponent();          
  19.         }  
  20.           
  21.         private void button1_Click(object sender, EventArgs e)  
  22.         {  
  23.             PythonEngine scriptEngine = new PythonEngine();  
  24.             scriptEngine.Execute(textBox1.Text);  
  25.         }  
  26.  
  27.     }  
  28.  
  29. }  
  30.  

     代码很简单,声明了一个scriptEngine 实例,直接用Execute执行代码即可。下面看看py的代码该怎么写:

  
  
  
  
  1. import clr  
  2. clr.AddReferenceByPartialName("System.Windows.Forms")  
  3. clr.AddReferenceByPartialName("System.Drawing")  
  4. from System.Windows.Forms import *  
  5. from System.Drawing import *  
  6. MessageBox.Show("Hello World!")  
  7.  

     第一句代码很重要,导入.net clr,用clr的AddReferenceByPartialName方法加载我们熟悉的System.Windows.Forms和System.Drawing库,最后可以直接执行.net中的MessageBox方法。

     运行后,直接单击button1,即可弹出一个对话框"Hello World!"

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

 

 

你可能感兴趣的:(脚本,示例,world,IronPython,hello)