IronPython2.7&C#4.0相互呼び出しメモ

2497 ワード

いくつかの资料を调べて、自分で更にテストした后に発见して、IronPythonはすでにとても便利でC#と互いに调节して使いました

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.IO;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using Microsoft.Scripting;

namespace ConsoleApplicationTest
{


public class Program
{
    public delegate void OutPut_delegate(object s);

    public string OutPut_instance(object s)
    {
        Console.WriteLine("  OutPut_Pri {0} ", s.ToString());
        return "return   in charp";
    }

    static public void OutPut_static(object s)
    {
        Console.WriteLine("in C#   OutPut {0} ", s.ToString());
    }

    static void OutPut(object s)
    {
        Console.WriteLine("C#   {0} ", s.ToString()); 
    }

    public int abc;

    static void Main(string[] args)
    {
        OutPut_delegate output = OutPut;
        DataTable dt = new DataTable();
        dt.Columns.Add("count", typeof(int));
        dt.Columns.Add("calc", typeof(int));
        dt.Rows.Add(1, null);

        var engine = Python.CreateEngine(); 
        var runtime = engine.Runtime;

        try 
        {
            Program program = new Program();
            dynamic test = runtime.UseFile(@"d:\test.py");
            int abc =100;

            //ref out python C#, 
            Console.WriteLine("return value is {0}", test.MyFunction(dt, ref abc, output, program));
            foreach (DataRow dr in dt.Rows)
                Console.WriteLine(dr["count"]);
            Console.WriteLine(program.abc);// 
            Console.WriteLine(abc);// 
        }
        catch (Exception ex)
        {
            var eo = engine.GetService<ExceptionOperations>();
            Console.WriteLine(eo.FormatException(ex));
        }
    }
}

}

# -*- coding: utf-8 -*-
# 3 
import clr, sys
clr.AddReference('ConsoleApplicationTest')
from ConsoleApplicationTest import *

def MyFunction(dt, abc, output, instance):
abc = 999
print instance
for row in dt.Rows:
    row["count"] = row["count"] * 2
print( output( "in python2" ) )
print instance.OutPut_instance("in python3")
instance.abc = 999
print dt
print output 

Program.OutPut_static(" ")
return "    in python"