[IronPython] Creating Python classes in IP2
Slide
slide.o.mix at gmail.com
Mon Mar 31 17:54:33 CEST 2008
I use the following for finding a class that implements a certain interface.
IAttributesCollection attrs =
IronPython.Runtime.Types.PythonModuleOps.Get__dict__(__main__);
foreach (KeyValuePair<object, object> attr in attrs)
{
IronPython.Runtime.Types.PythonType attr_type =
attr.Value as IronPython.Runtime.Types.PythonType;
if (attr_type != null)
{
foreach (IronPython.Runtime.Types.PythonType
dt in attr_type.BaseTypes)
{
if (dt.UnderlyingSystemType != null &&
dt.UnderlyingSystemType == typeof(T))
{
CodeContext context = new
CodeContext(__main__.Scope, _context, new ModuleContext(__main__));
inst = (T)attr_type.CreateInstance(context);
break;
}
}
}
}
Is there a way that is more portable between the different languages?
On Sun, Mar 30, 2008 at 4:53 AM, Curt Hagenlocher <curt at hagenlocher.org> wrote:
> On Sun, Mar 30, 2008 at 2:59 AM, Paul Turbett <sls at iinet.net.au> wrote:
> >
> > I've looked through the DLR hosting spec, and experimented a bit, but I
> > can't see how to get the same thing working with DLR hosting. So, how do
> > I create instances of python classes from C#?
>
> This is what works for me:
>
> ScriptRuntime runtime = ScriptRuntime.Create();
> ScriptEngine engine = runtime.GetEngine("py");
>
> // These next two lines are needed if you expect to be able to import System
> // without manually loading the assembly through Python
> // runtime.LoadAssembly(typeof(string).Assembly);
> // runtime.LoadAssembly(typeof(System.Diagnostics.Debug).Assembly);
>
> // File foo.py contains class Foo
> ScriptScope scope = runtime.ExecuteFile("foo.py");
> object theClass;
> scope.TryGetVariable("Foo", out theClass);
> object theValue = PythonCalls.Call(theClass);
>
> --
> Curt Hagenlocher
> curt at hagenlocher.org
>
>
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
>
--
slide-o-blog
http://slide-o-blog.blogspot.com/
More information about the Ironpython-users
mailing list