Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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
Anonymous
July 23, 2008
PingBack from http://blog.a-foton.ru/2008/07/how-to-create-ironpython-objects-of-types-defined-in-c/Anonymous
January 18, 2009
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)"