Using Compiled Python Classes from .NET (c

From IronPython Cookbook

Revision as of 19:51, 27 January 2010 by Djlawler (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)

You can compile an IronPython class to a DLL and then use IronPython hosting in c# to access the methods (this is for IronPython 2.6 and .Net 2.0).

Create a c# program like this:

   using System;
   using System.IO;
   using System.Reflection;
   using IronPython.Hosting;
   using Microsoft.Scripting.Hosting;
   // we get access to Action and Func on .Net 2.0 through Microsoft.Scripting.Utils
   using Microsoft.Scripting.Utils;
   namespace TestCallIronPython
       class Program
           public static void Main(string[] args)
               Console.WriteLine("Hello World!");
               ScriptEngine pyEngine = Python.CreateEngine();
               Assembly myclass = Assembly.LoadFile(Path.GetFullPath("MyClass.dll"));
               ScriptScope pyScope = pyEngine.Runtime.ImportModule("MyClass");
               // Get the Python Class
               object MyClass = pyEngine.Operations.Invoke(pyScope.GetVariable("MyClass"));
               // Invoke a method of the class
               pyEngine.Operations.InvokeMember(MyClass, "somemethod", new object[0]);
               // create a callable function to 'somemethod'
               Action SomeMethod2 = pyEngine.Operations.GetMember<Action>(MyClass, "somemethod");
               // create a callable function to 'isodd'
               Func<int, bool> IsOdd = pyEngine.Operations.GetMember<Func<int, bool>>(MyClass, "isodd");
               Console.Write("Press any key to continue . . . ");

make a trivial python class like this:

   class MyClass:
       def __init__(self):
           print "I'm in a compiled class (I hope)"
       def somemethod(self):
           print "in some method"
       def isodd(self, n):
           return 1 == n % 2

compile it (I use SharpDevelop) but the clr.CompileModules method should work also. Then shove the compiled MyClass.dll into the directory where the compiled c# program lives and run it. You should get this as the result:

   Hello World!
   I'm in a compiled class (I hope)
   in some method
   in some method
   Press any key to continue . . .