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

本文介绍了如何在Visual Studio 2010的C#项目中使用IronPython库调用和整合Python函数。通过创建Console应用程序,引入IronPython相关DLL,并编写C#代码来执行Python的定义函数、类,以及从外部Python文件导入并执行函数。示例中展示了如何执行Python的加法函数、打印语句,以及实例化Python类。同时强调了`TestPython.py`文件的位置要求,该文件包含一个返回年份的Python函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值