Calling C# Class from DLR (Iron Python)

Jul 13, 2010 at 9:06 AM
Hi all, I have a project I'm working on where I need to allow users to call classes that I have created in C# from scripts they have written in Python. I have implemented the DLR fine, and the user scripts run perfectly - even to the point of creating forms - but now I need to allow access to public classes that I have created that do certain things, kind of like an API for the users to make use of should they need it. However, I cannot for the life of me work out how to expose the classes to the DLR. Could someone point me in the right direction please? Or even better, a small example - I've searched for days and can find very little. Thank you, in advance.
Jul 13, 2010 at 11:07 AM
Edited Jul 13, 2010 at 11:09 AM
So far, I have this:
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cl
{
    public class Class1
    {
        public String GetMeAString()
        {
            return "this is a string";
        }
    }
}

--Python DLR

import clr
clr.AddReference("cl")
import cl

ws = cl
print ws.GetMeAString()

[/code]
When I run it, I get the error: attribute 'GetMeAString' of 'namespace#' object is read-only PS. I have no idea how to format here: standard BB formatting seems to be ignored.
Jul 13, 2010 at 1:12 PM

The following Python code should work. You need to create an instance of the class in order to call a member on it.

import clr
clr.AddReference("cl")
from cl import Class1
ws = Class1()
print ws.GetMeAString()
Jul 13, 2010 at 1:36 PM
oops - quite right too! I realised what I had done, and ended up with code identical to yours. Thank you very much!