python与C#的互相调用

来源:互联网 发布:sqlserver exists in 编辑:程序博客网 时间:2024/06/06 20:39
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()
0 0
原创粉丝点击