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目录下
TestPython.py内容如下:
def getYear():
return 2012;
- VS2010 下C#调用与整合python函数
- VS2010中C#调用C函数
- VS2010中C#调用C函数
- VS2010中C#调用C函数
- VS2010中C#调用C函数
- VS2010中C#调用C函数
- VS2010下,C++调用python的设置
- VS2010 C# 调用Ironpython
- C#与C++函数调用
- python函数创建与调用
- VS2010下,C++调用python的Runtime error R6034解决方法
- MessageBox函数在VC6与VS2010中的调用
- VS2010下安装python
- VS2010 下 使用 Python
- python与C#的互相调用
- python与C#的互相调用
- VS2010 C# 调用Web Service
- arm-linux下python调用c函数
- uboot启动参数设置和内核引导方法总结
- HTTP/FTP客户端开发库:libwww、libcurl、libfetch 以及更多
- WPF详解2.0-WPF布局面板
- 走几步回头看看企业即时通讯
- Linux-C实现GPRS模块发送短信 作者:冯建
- VS2010 下C#调用与整合python函数
- 检索最多城市的省sql
- 二十多年前格式工厂
- 提供转换编码后的供下载用的文件名(自己整理工具类)
- PHP单例模式的本质
- 程序员必知的8大排序(三)-------冒泡排序,快速排序(java实现)
- JNI的实现流程
- 全排列(模板实现)
- ROWID走索引之嫌疑犯抓获