IronPython C#与Python相互调用

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 est.py");
            var engine = Python.CreateEngine();
            var scope = engine.CreateScope();
            var source = engine.CreateScriptSourceFromFile(@"E:Test est.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:TestPyConsoleTestPyConsoleTestinDebug')
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 删除所有中文即可使用

原文地址:https://www.cnblogs.com/Justsoso-WYH/p/7793926.html