简体   繁体   中英

Injecting c# type into Ironpython

Right now I can use following code to access my c# types in IronPython as follow

import clr
clr.AddReference('myDLL.dll')
import myType
obj = myType()

however I don't want script developers to have clr.AddReference('myDLL.dll') line in Python source code, and inject myDLL.dll (and/or a c# class) directly from c# into ScriptEngine so the previous code will be something similar to:

import myType

obj = myType()  

how can I achieve this?

You can solve this problem using following solution :

ScriptRuntime runtime = Python.CreateRuntime();
runtime.LoadAssembly(Assembly.GetAssembly(typeof(MyNameSpace.MyClass)));
ScriptEngine eng = runtime.GetEngine("py");
ScriptScope scope = eng.CreateScope();
ScriptSource src = eng.CreateScriptSourceFromString(MySource, SourceCodeKind.Statements);
var result = src.Execute(scope);

Now, in python script you can write:

from MyNameSpace import *
n=MyClass()
print n.DoSomeThing()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM