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

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>("adder");
            var hello = scope.GetVariable>("hello");


            var myClass=scope.GetVariable>("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 options = new Dictionary();
            options["Debug"] = true;


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


        }
    }
}


结果:

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


TestPython.py内容如下:

def getYear():
   return 2012;

你可能感兴趣的:(VS2010 下C#调用与整合python函数)