[IronPython] Using a C# class in IronPython

Mark Grice markjoel60 at gmail.com
Wed Feb 17 15:58:29 CET 2010


I'm not sure if this helps, but I use a C# class in my IronPython, and it
works fine.

Class is defined using the shorthand get; set;

ie:

public class ScreenTags
    {
        public String appWindowName { get; set; }
        public String fieldName { get; set; }
        public bool isDataField { get; set; }
        public bool isManual { get; set; }
        public String screenLabel { get; set; }
        public String description { get; set; }
}

(In actuality, it is a lot more than this, consisting of other classes,
methods, etc...)

Now, it may be bad practice, but I then simply use an object reference in
Python, and assume it was instantiated. In other words, as far as Python
is concerned, there is an instantiated object of ScreenTags called "screen".

Python simply calls this whenever it wants to do something:

ie. screen. appWindowName  = "ThisName"

I create the screen object in my C# code, and then add it as a reference to
the python scope before I call the IronPython engine. So, on the C# side I:

                scptEngine = Python.CreateEngine();
                scptRuntime = scptEngine.Runtime;
                scptScope = scptEngine.CreateScope();
                AddAssemblies(scptRuntime);       // call if you need to add
other libraries, such as my class

And before I actually call the Engine, I set the class in the Python scope
-- still in C#:

                ScreenTags SOA_screen = new ScreenTags();
                scptScope.SetVariable("screen", SOA_screen);
                scptSource =
scptEngine.CreateScriptSourceFromFile(scriptFile);  // scriptFile is Python
code
                scptSource.Execute(scptScope);

This is working fine. The class is actually really a loaded class, and it
has all kind of goodies in it (ie pop up Windows forms, calls out to
unmanaged code... all sorts of stuff). I never have a problem with any of
it.

I don't know if this helps (or even if it is good practice!) but it is
working here.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20100217/a14ef4c5/attachment.html>


More information about the Ironpython-users mailing list