python与C#的互相调用


转至: http://blog.csdn.net/hanghangaidoudou/article/details/70172162

python与C#的互相调用


一、C#调用python


新建一个项目,添加引用:IronPython.dll,Microsoft.Scripting.dll(在IronPython的安装目录中)。


创建一个文本文件命名为hello.py,把该文件添加的当前的项目中,并设置为总是输出。


#hello.py
def welcome(name):
return "hello" + name


调用hello.py文件中的方法:
static void main(string[] args)
{
ScriptRuntime pyRunTime=Python.CreateRuntime();
dynamic obj=pyRunTime.UseFile("hello.py");


Console.Write(obj.welcome("Nick"));
Console.ReadKey();
}




二、Python调用C#


示例一:调用dll中的方法
1.先准备一个C#写的dll,名称为IronPython_TestDll.dll
using System;
using System.Collections.Generic;
using System.Text;
namespace IronPython_TestDll
{
public class TestDll
{
public static int Add(int x, int y)
{
return x + y;
}
}


public class TestDll1
{
private int aaa = 11;
public int AAA
{
get { return aaa; }
set { aaa = value; }
}
public void ShowAAA()
{
global::System.Windows.Forms.MessageBox.Show(aaa.ToString());
}


}
}


2.调用C#的dll中的方法
import clr
clr.AddReferenceByPartialName("System.Windows.Forms")
clr.AddReferenceByPartialName("System.Drawing")
from System.Windows.Forms import *
from System.Drawing import *
clr.AddReferenceToFile("IronPython_TestDll.dll")
from IronPython_TestDll import *


a=12
b=6
#静态方法可以直接调用
c=TestDll.Add(a,b)
MessageBox.Show(c.ToString())


#普通方法需要先定义类
td=TestDll1()
td.AAA=100
td.ShowAAA()




示例二:动态执行python代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using IronPython.Hosting;
namespace TestIronPython
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


private void button1_Click(object sender, EventArgs e)
{
PythonEngine scriptEngine = new PythonEngine();


//设定dll文件所在的目录
scriptEngine.AddToPath(Application.StartupPath);


//textBox1.Text中写的是python代码,但调用的是dll中的方法
scriptEngine.Execute(textBox1.Text);
}
}
}


//textBox1.Text中写的是如下代码,会计算弹出100的提示框。
a=12
b=6
c=TestDll.Add(a,b)
MessageBox.Show(c.ToString())


td=TestDll1()
td.AAA=100
td.ShowAAA()

优质内容筛选与推荐>>
1、django orm补充 only/defer/ selectd_related
2、jQuery选择器
3、Python 项目实践二(生成数据)第一篇
4、MySql 分页关键字(limit)
5、利用二分查找查找有序列表中是否存在某个值


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号