Dynamic Language Programming with Python – Sample Implementation

DLR is a great invention by Microsoft .NET 4.0 along with Dynamic Typing

The Dynamic Language Runtime (DLR) is piece of technology that unifies dynamic programming on the .NET platform, the same way the Common Language Runtime (CLR) has been a common platform for statically typed languages. CLR always has dynamic capabilities ,DLR is on top of CLR.

Currently IronPython and IronRuby is supported , below is an example of how to consume a python class in C#.

You may need to download the IronPython Library from the below link and install , include those references to your project.

http://ironpython.codeplex.com/

Assume you have python class like below

Calc.py

class Calculator:

   def add(self, argA, argB):

      return argA+argB

   def sub(self, argA, argB):

      return argA-argB

The above said class can be accessed in C# like below

using IronPython.Hosting;

static void Main(string[] args)

{

var enginePY = Python.CreateEngine();

  dynamic calcPYObject = enginePY.ExecuteFile(@”C:\Uday\DynamicPY – Demo Application\DynamicPY – Demo Application\calc.py”);

dynamic calc = calcPYObject.Calculator();

Console.WriteLine(calc.__class__.__name__);

//write ‘Calculator’

double X = 25;

double Y = 10;

double result;

result = calc.add(X, Y);

Console.WriteLine(“{0} + {1} = {2}”, X, Y, result);

 result = calc.sub(X, Y);

Console.WriteLine(“{0} – {1} = {2}”, X, Y, result);

Console.WriteLine(“Press any key to close the application…”);

Console.Read();

        }

    }

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s