利用C#4.0调用IronPython脚本

利用C#4.0调用IronPython脚本

 

 

VS2010C#4.0新增加了dynamic功能,为调用IronPython以及IronRuby提供了方便。本文为大家说明如果在C#4.0中调用IronPython中的函数以及类。

1.        Demo使用的VS2010的版本是RC版,微软还没有将IronPython的库集成进来,所以在VS2010中调用IronPython,先要到CodePlex上下载IronPythonFor .NET4.0的安装程序,Urlhttp://ironpython.codeplex.com/releases/view/40146

2.        编写一个IronPython脚本文件“Test.py,代码如下:

#coding gb2312

import clr

class MyService(object):

    def GetData(self, value):

        return "hello" + value

 

def MyFunction(name):

    return "hello " + name

在该脚本中定义了一个MyService类,在MyService类中定义了一个GetData方法。在该脚本中同时又定义了一个MyFunction的函数。

3.        建立一个应用程序,并引用刚才下载的IronPython安装目录下的几个DLL文件,如下所示:

4.        Python脚本放在应用程序所在的目录,用来调用的C#代码如下所示:

      var python = Python.CreateRuntime();

            dynamic script= python.UseFile("a.py");

            //调用Python里的类

                            var service = script.MyService();

            string result=service.GetData("aaa");

            MessageBox.Show(result);

 

            //调用中的函数

                            result = script.MyFunction("aaa");

            MessageBox.Show(result );

5.        这里比较重要的是dynamic关键字的使用,它可以实现代码的运行时载入,速度会比反射要稍快点。

今天就写到这儿,如何大家需要技术支援,请给我发Email:warensoft@foxmail.com

原文地址:https://www.cnblogs.com/warensoft/p/1680634.html