Re.Mark

My Life As A Blog

Use .NET classes in IronPython

leave a comment »

It’s really simple to use a .NET class in IronPython.  The first thing to remember is that you’ll need to add a reference (just like you would in .NET).  To do that you use the AddReference method of the clr module.  In the case of an assembly you’ve written, IronPython needs to be able to find it, which means it needs to be in sys.path.  It turns out that you can add the path to your assembly by using the append method of sys.path.  Here’s a simple example.  First, let’s create a simple class called User in C# in a solution called SampleClasses:

namespace SampleClasses

{

    public class User

    {

        public string Name{ get; set;}

        public DateTime DateOfBirth { get; set; }

    }

}

For the sake of simplicity, let’s copy the dll to a folder called lib on the C drive.  OK.  Time to fire up IronPython (which I’m going to assume you’ve already installed.)  Open a command prompt and type “ipy”.  You should see something like the following:

image

Next, let’s ensure the SampleClasses assembly is available to IronPython:

>>>import sys
>>>sys.path.append(‘C:\\lib’)

Once we’ve done that we can add a reference:

>>>import clr
>>>clr.AddReference(‘SampleClasses’)

Now, we need to import the User name from the SampleClasses namespace:

>>>from SampleClasses import User

We’re all set.  Create an instance of user and set one of the properties:

>>>a.User()
>>>a.Name=’Bob’
>>>a.Name
‘Bob’

That’s all there is to it.  Now you can go and experiment with IronPython and classes you’ve already written in .NET.

Advertisements

Written by remark

June 4, 2009 at 2:49 pm

Posted in .NET, c#, Python, Software

Leave a Reply

Fill in your details below or click an icon to log in:

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

%d bloggers like this: