1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C#嵌入IronPython脚本示例(hello world)

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

时间:2023-02-26 08:20:08

相关推荐

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

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

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

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

下面是C#中的代码:

using System;

using System.Collections.Generic;

using ponentModel;

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!"

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。