通过DLR Hosting APIs把DLR语言(如IronPython、IronRuby)嵌入到.NET应用程序
IronPython是Python编程语言的一种开源实现,它能够与.NET Framework框架紧密集成。IronPython可以使用.NET Framework和Python标准类库,而.NET语言也可以很简单地使用Python代码。
使用Visual Studio创建一个单元测试项目,添加Microsoft.CSharp.dll的引用,通过Nuget添加IronPython包,在项目中添加下面代码,运行单元测试。
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProjectIronPython { [TestClass] public class UnitTest1 { //基本用法 [TestMethod] public void TestMethod1() { //创建脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //编写脚本 var pythonScript = "1+1"; //通过引擎执行脚本 var sum = engine.Execute<int>(pythonScript); //判断c#中执行和IronPython中执行结果是否相等 Assert.AreEqual(1 + 1, sum); } //传入变量 [TestMethod] public void TestMethod2() { //创建脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //通过引擎创建作用域 var scope = engine.CreateScope(); //创建变量 var a = 1; var b = 2; //在作用域中设置变量 scope.SetVariable("a", a); scope.SetVariable("b", b); //待执行脚本 var pythonScript = "a+b"; //通过引擎创建脚本源 var scriptSource = engine.CreateScriptSourceFromString(pythonScript); //在作用域上执行脚本源 var sum = scriptSource.Execute<int>(scope); //判断c#中执行和IronPython中执行结果是否相等 Assert.AreEqual(a + b, sum); } //传入函数 [TestMethod] public void TestMethod3() { //创建脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //通过引擎创建作用域 var scope = engine.CreateScope(); //创建函数 Func<int,int> fn = (i) => i * i; //在作用域中设置变量 scope.SetVariable("fn", fn); //待执行脚本 var pythonScript = "fn(4)"; //在作用域上执行脚本源 var scriptSource = engine.CreateScriptSourceFromString(pythonScript); //在作用域上执行脚本源 var result = scriptSource.Execute<int>(scope); //判断c#中执行和IronPython中执行结果是否相等 Assert.AreEqual(fn(4), result); } //IronPython定义函数,.NET调用 [TestMethod] public void TestMethod4() { //创建脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //编写脚本 var pythonScript = "lambda x:x*x"; //动态类型访问python对象 dynamic result = engine.Execute(pythonScript); //判断c#中执行和调用IronPython执行结果是否相等 Assert.AreEqual(4 * 4, result(4)); } //编译运行 [TestMethod] public void TestMethod5() { //创建脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //通过引擎创建作用域 var scope = engine.CreateScope(); //创建函数 Func<int, int> fn = (i) => i * i; //在作用域中设置变量 scope.SetVariable("fn", fn); //待执行脚本 var pythonScript = "fn(4)"; //在作用域上执行脚本源 var scriptSource = engine.CreateScriptSourceFromString(pythonScript); //编译脚本源 var compileCode = scriptSource.Compile(); //在作用域上执行脚本源 var result = compileCode.Execute<int>(scope); //判断c#中执行和IronPython中执行结果是否相等 Assert.AreEqual(fn(4), result); } } }