Wednesday, January 15, 2014

IronPython with C#

using python in c#
http://ironpython.codeplex.com/releases/view/28125
http://blogs.msdn.com/b/charlie/archive/2009/10/25/hosting-ironpython-in-a-c-4-0-program.aspx

started console project.
works!

Test.cs
namespace TestPython
{
    public class Test
    {
        int a = 10;
        public int A { get { return a; } }
        public void Method1()
        {
            Console.WriteLine(a);
        }
        public int Method2(int b)
        {
            return a + b;
        }
    }
}

Test.py
import sys
import clr

class MyPyClass:
  myvar = 123
  def _init_(self):
    print "constructor"
  def m1(self):
    print self.myvar

def Simple():
  print "Hello from Python"
  a = 3
  a = a *4
  print a

  # instantiate C# class
  clr.AddReference('TestPython') # can be replaced with "ipy.LoadAssembly(System.Reflection.Assembly.GetExecutingAssembly());" in C#, if necessary
  from TestPython import *
  b = Test();
  b.Method1();

Program.cs
namespace TestPython
{
    class Program
    {
        static void Main(string[] args)
        {
            var ipy = Python.CreateRuntime();
            dynamic test = ipy.UseFile("Test.py");
            test.Simple();

            // use python class in c#
            var instance = test.MyPyClass();
            instance.m1();
         
            Console.WriteLine("Bye");
            Console.ReadLine();
        }
    }
}

No comments: