Use .NET classes in IronPython
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:
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.