[IronPython] .NET can see Python classes?

Michael Foord fuzzyman at voidspace.org.uk
Sun Aug 5 12:28:38 PDT 2007


Ori wrote:
> you can try the following code:
>
> PythonEngine engine = new PythonEngine();
> EngineModule module = engine.CreateModule();
> engine.Execute(handleCode(code, def), module); # code contains definition
> for python class 'PyClass'
> UserType ptype = module.Globals["PyClass"] as UserType;
> object obj = Ops.Call(ptype);
>   
Here is a full example:

using System;
using IronPython.Hosting;
using IronPython.Runtime.Types;
using IronPython.Runtime.Operations;

namespace TestPythonConsole
{
    class Program
    {
        static void Main()
        {
            string code = "import 
clr\r\nclr.AddReference('TestPythonConsole')\r\nfrom TestPythonConsole 
import Test\r\nclass X(Test):\r\n     def test(self):\r\n        return 
'hello'\r\n\r\n";
            PythonEngine engine = new PythonEngine();
            EngineModule module = engine.CreateModule();
            engine.DefaultModule = module;
            engine.Execute(code);
            UserType ptype = module.Globals["X"] as UserType;
            Test obj = Ops.Call(ptype) as Test;
            Console.WriteLine(obj.test());
        }
    }

    public class Test
    {
        virtual public string test()
        {
            return "goodbye";
        }
    }

}

The Python code imports 'Test' (it has to add the right reference to the 
assembly first). It then subclasses 'Test' in a class called X.

The class we pull out of the Python engine globals is called and the 
result cast to Test.

Calling the method 'test' calls the subclass rather than the parent class.

I hope that helps.

Michael Foord
http://www.ironpython.info/


>
> Darren Govoni-2 wrote:
>   
>> Hi,
>>   Can .NET see python defined classes or objects? I define a class in
>> Python
>> but one of my .NET classes tries to find it via reflection and it cannot.
>> I saw a post about this that is over a year old saying it was not then
>> supported.
>>
>> Could this possible in IP 2.0?
>>
>> thank you,
>> D
>> _______________________________________________
>> Users mailing list
>> Users at lists.ironpython.com
>> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
>>
>>
>>     
>
>   



More information about the Users mailing list