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);

    }

}

Comments