Welcome to MSDN Blogs Sign in | Join | Help

How to create IronPython objects of types defined in C#

The DLR Hosting API lets the hosted script instantiate objects of types defined in the hosting C# / VB module. This post describes how to do that using the appropriate methods from the API. Here are the simple steps -

1)    Load the assembly containing the type in to the ScriptRuntime object

ScriptRuntime runtime = ScriptRuntime.Create();

runtime.LoadAssembly( Assembly.GetAssembly( typeof( n1.MyType1)));

 

2)    Import the namespace/type inside the script

from n1 import *

 

3)    Create an object of the type and invoke members

n=MyType1()

print n.Name

Here’s the full sample

using System.Scripting;

using Microsoft.Scripting.Hosting;

using System.Reflection;

 

namespace n1 {

    public class MyType1 {

        public string Name { get; set; }

        public MyType1() {

            Name = "MyType1";

        }

    }

}

 

public class Program {

    static void Main(string[] args) {

        string code = @"from n1 import *

 

n=MyType1()

print n.Name";

       

        ScriptRuntime runtime = ScriptRuntime.Create();

        runtime.LoadAssembly( Assembly.GetAssembly( typeof( n1.MyType1)));

 

        ScriptEngine eng = runtime.GetEngine("py");

        ScriptScope scope = eng.GetEngine("py").CreateScope();

       

        ScriptSource src = eng.CreateScriptSourceFromString( code, SourceCodeKind.Statements);

        src.Execute(scope);

    }

}
Published Wednesday, July 23, 2008 7:45 PM by seshadripv

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# a-foton » How to create IronPython objects of types defined in C#

# re: How to create IronPython objects of types defined in C#

Is there a way to import all types from namespace "n1" programmatically, so it won't be neccessary to add "from n1 import *" inside your script. Just as it was possible in Ironpython1 with "EngineModule.Import(Type type)"

Monday, January 19, 2009 6:49 AM by jigglingfrog

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker