1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > ironpython使用dictionary_在C#环境中动态调用IronPython脚本(一)

ironpython使用dictionary_在C#环境中动态调用IronPython脚本(一)

时间:2024-06-04 10:38:31

相关推荐

ironpython使用dictionary_在C#环境中动态调用IronPython脚本(一)

本文讲述用C#调用Ironpython运行环境,解析并运行动态pyhton脚本。这种情况应用在那些需要滞后规定行为的场合,例如,动态计算项(计算引擎),用户可以自定义计算内容、计算公式等。

本文的代码适用于IronPython 2.7(需要下载及安装)及C#4.0,由于IronPython早期版本提供的Hosting API不同,对于网上搜索得到的代码,如果是早期版本代码(多数如此),并不能编译通过,所以本文强调代码的版本问题。

本文代码需要引用两个命名空间IronPython和Microsoft.Scripting (文件位置分别为IronPython 2.7的安装目录下的IronPython.dll和Microsoft.Scripting.dll)。

一、最简单的例子

先看一个最简单的例子,C#环境与Python环境没有数据联系。

publicstaticvoidtest1()

{

varengine=IronPython.Hosting.Python.CreateEngine();

engine.CreateScriptSourceFromString("print'helloworld'").Execute();

Console.ReadLine();

}

如果IronPython环境建立好,运行test1(),就会得到正确的结果。如果只想运行一段脚本,就是这般简单。

二、C#环境调用Python环境函数

以上的例子没有实用价值,再看第二个例子,这个例子演示了如何从C#环境调用Python环境中的函数以及类中方法。

publicstaticvoidtest2()

{

varengine=Python.CreateEngine();

varscope=engine.CreateScope();

varsource=engine.CreateScriptSourceFromString(

"defadder(arg1,arg2):\n"+

"returnarg1+arg2\n"+

"\n"+

"deffun(arg1):\n"+

"tel={'jack':4098,'sape':4139}\n"+

"fork,vinarg1.iteritems():\n"+

"tel[k]=v\n"+

"returntel\n"+

"\n"+

"classMyClass(object):\n"+

"def__init__(self,value):\n"+

"self.value=value\n");

source.Execute(scope);

varadder=scope.GetVariable>("adder");

Console.WriteLine(adder(2,2));

varfun=scope.GetVariable>("fun");

IronPython.Runtime.PythonDictionaryinputDict=newIronPython.Runtime.PythonDictionary();

inputDict["abc"]="abc";

inputDict["def"]=456;

objectres=fun(inputDict);

IronPython.Runtime.PythonDictionaryoutputDict=resasIronPython.Runtime.PythonDictionary;

foreach(varkinoutputDict.Keys)

{

Console.WriteLine("key:"+k.ToString()+"val:"+outputDict[k].ToString());

}

varmyClass=scope.GetVariable>("MyClass");

varmyInstance=myClass("hello");

Console.WriteLine(engine.Operations.GetMember(myInstance,"value"));

}

上面代码中,python中有两个函数和一个类,第一个函数的参数是简单数据类型,第二个是复杂数据类型(关于两个环境下复杂数据类型的对应,下面将论述)。无论是类还是函数,C#的调用方法都是通过ScriptScope.GetVariable,它的函数定义如下:

T GetVariable(string name);

ScriptScope还有一个更“安全”的方法

boolTryGetVariable(string name, out T value);

可以完成相似的操作。

这个例子,可以扩展C#的应用,例如,python有丰富的数学计算库,而C#在这方面较欠缺,这时,就可以采用上面的方式,计算部分采用现成的python库,而主控程序采用C#编制。

三、在Python环境中调用C#环境函数

现在看第三个例子,如果Python运行逻辑复杂,需要在运行过程中调用C#函数怎么办?

publicstaticvoidtest3()

{

varengine=Python.CreateEngine();

varscope=engine.CreateScope();

scope.SetVariable("my_object_model",newCSharpClass());

stringpythonscript=

"deffun(arg1):\n"+

"result=arg1+1\n"+

"returnresult\n"+

"adder=fun(5)+my_object_model.Foo(2)\n";

engine.CreateScriptSourceFromString(pythonscript).Execute(scope);

Console.WriteLine(scope.GetVariable("adder"));

}

ClassCSharpClass

{

publicintFoo(intarg)

{

returnarg+1;

}

}

这个例子中,创建CShparpClass类,并将其作为“变量”传到Python环境中,在Python中就可以调用了。注意到C#中的类名可以和Python中不一样。

四、在Python环境中动态调用C#库

在这种情况下,Python脚本和C#库都是“滞后”于主应用才编写出来的,可以满足用户现场定制行为(采用Python脚本),并且可以给Python脚本传入现场定制的参数。

首先,建立一个C#库,代码如下:

namespaceLibforPython

{

publicclassPythonLib

{

publicintTest(intx,stringop)

{

switch(op.ToUpper())

{

case"INC":

returnx+1;

case"DEC":

returnx-1;

}

returnx+1;

}

}

}

编译成LibforPython.dll后拷贝到主运行程序的运行目录(二者同目录)。调用代码如下:

publicstaticvoidtest4()

{

varengine=Python.CreateEngine();

varscope=engine.CreateScope();

engine.Runtime.LoadAssembly(Assembly.LoadFrom("LibforPython.dll"));stringpythonscript=

"fromLibforPythonimportPythonLib\n"+

"o=PythonLib()\n"+

"res=o.Test(6,'add')\n";

engine.CreateScriptSourceFromString(pythonscript).Execute(scope);

Console.WriteLine(scope.GetVariable("res"));

}

运行以上程序即可。这个例子中,LibforPython.dll是在运行时才引入Python环境中的。对于预先已知的Python可能用到的接口,才用例三的办法更好些,对于预先无法预先定义或“遗忘”的接口,采用本例比较适合。

五、总结

将Python环境“寄宿”于C#环境,进而动态执行用户自定义的脚本,是应用可配置性、灵活性的一种体现(其他动态语言也可以这么做,以Ironpython比较简单)。这一过程包括以下三步:

var engine = Python.CreateEngine();

var scope = engine.CreateScope();

var source = engine.CreateScriptSourceFromString(“…”);

source.Execute(scope);

Python环境与宿主环境的交互(参数传入、传出),则通过ScriptScop的GetVariable和SetVariable进行。

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