• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

IronPythonC#与Python相互调用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

ironphy  microsoft.scripting dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using Common;

namespace PyConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //ScriptRuntime pyRuntime = Python.CreateRuntime();
            //dynamic py = pyRuntime.UseFile(@"E:\Test\test.py");
            var engine = Python.CreateEngine();
            var scope = engine.CreateScope();
            var source = engine.CreateScriptSourceFromFile(@"E:\Test\test.py");
            source.Execute(scope);
            var say_hello = scope.GetVariable<Func<object>>("say_hello");
            say_hello();
            var get_text = scope.GetVariable<Func<object>>("get_text");
            var text = get_text().ToString();
            Console.WriteLine(text);
            var add = scope.GetVariable<Func<object, object,object>>("add");
            var name = scope.GetVariable<Func<object,object>>("get_name");
            int[] ints = { 1, 2, 3, 4 };
            List<int> list = new List<int>();
            Dictionary<int, int> dic = new Dictionary<int, int>();
            int i = 0;
            SimpleTest test = new SimpleTest();
            var result1 = name(test);  Python调用C#
            list.AddRange(ints);
            var result2 = add(list, i);  传递参数并返回值
            Console.WriteLine(result2);
            
            //var result1 = add("hello", i.ToString());
            //Console.WriteLine(result1);
            Console.Read();
        }
    }
}

以下C#代码测试Python调用C#时使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public class SimpleTest
    {
        public string GetName()
        {
            return "C#";
        }
    }
}

 

Python代码

import clr
import sys
sys.path.append(r'E:\Test\PyConsoleTest\PyConsoleTest\bin\Debug')
clr.AddReferenceToFile("Common.dll")
from Common import *
def say_hello():
    print "hello!"


def get_text():
    return "text from hello.py"


def add(arg1,arg2):  传递参数返回参数
    #var y
    for x in arg1:
        arg2 += x
    return arg2
    #print y
    #return arg1+arg2;
def get_name(SimpleTest): 调用方法返回
    return SimpleTest.GetName()

 

PS:如果你的Python没有设置encoding 删除所有中文即可使用


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c#部分---用函数的四种格式做一元二次方程发布时间:2022-07-10
下一篇:
C#zip压缩文件的功能发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap