VS2010 下C#调用与整合python函数

来源:互联网 发布:刘德华唱功知乎 编辑:程序博客网 时间:2024/06/07 01:15

1.下载IronPython2.7(http://ironpython.codeplex.com/)

2.安装IronPython2.7

3.VS2010创建Console程式,参考引用C:/Program Files/IronPython 2.7/IronPython*.dll,Microsoft.*.dll

如:

4.Console代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using IronPython.Hosting;
using IronPython.Compiler;
using IronPython.Modules;
using IronPython.Runtime;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
namespace PythonConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var engine = Python.CreateEngine();
            var scope = engine.CreateScope();
            //注意要有空格 否则会导致缩进对不上位置 即expected an indented block 错误
            var py = "def adder(arg1,arg2):\n"+"   return arg1 + arg2 \n"+"\n"+"def hello(arg1):\n"+"   return 'hello'+arg1 \n"+"\n"+"class MyClass(object):\n"+"  def __init__(self,value):\n"+"    self.value=value\n"; //__init__ 是两个下划线


            var code = engine.CreateScriptSourceFromString(py,SourceCodeKind.Statements);
            code.Execute(scope);
            var adder = scope.GetVariable<Func<object ,object,object >>("adder");
            var hello = scope.GetVariable<Func<object,object>>("hello");


            var myClass=scope.GetVariable<Func<object,object>>("MyClass");
            var myInstance = myClass("IronPython");


            Console.WriteLine(adder(1,2));
            Console.WriteLine(hello("Mark"));


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


            engine.CreateScriptSourceFromString("print 'Hello Python'").Execute();
            Console.WriteLine();
            engine.Execute("print 'Hello World'"); //严格要求 没有空格的地方不要加空格


            Dictionary<string, object> options = new Dictionary<string, object>();
            options["Debug"] = true;


            ScriptRuntime pyRuntime = Python.CreateRuntime(options);
            dynamic scriptScope = pyRuntime.UseFile("TestPython.py");
            Console.WriteLine(scriptScope.getYear());
            Console.ReadLine();


        }
    }
}


结果:

而关键文件TestPython.py必须要放在项目/bin/debug目录下

image


TestPython.py内容如下:

def getYear():
   return 2012;

原创粉丝点击