日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

python与C#的互相调用

發布時間:2023/11/30 C# 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python与C#的互相调用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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()

總結

以上是生活随笔為你收集整理的python与C#的互相调用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。