IronPython exposing .Net type to the runtime engine

只谈情不闲聊 提交于 2019-12-05 00:27:35

问题


I'm looking to expose specific .Net types to the IronPython runtime. I can do this:

ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.Runtime.LoadAssembly(typeof(Program).Assembly); // current assembly with types

But that exposes all types to the runtime. Is selective type loading possible?


回答1:


No, you must load the entire assembly.

This is internally managed by the ScriptDomainManager, which only keeps a list of loaded assemblies, not types.

The best option would be to make your assembly only expose the types publicly that you want available within your Python environment, and leave the rest of the types internal.




回答2:


There are actually a few options none of them automatic though. First you'll need to call DynamicHelpers.GetPythonTypeFromType(typeof(TypeToInject)) to get a PythonType object which will actually be usable. Then you can either:

  1. Inject it into ScriptRuntime.Globals and it'll be available for import

  2. Inject it into a ScriptScope against some code you're going to be running

  3. Inject it into the PythonType.GetBuiltinModule() scope and it'll be available w/o importing




回答3:


You can expose a single object in C# like so:

ScriptScope scope = runtime.CreateScope(); //get a scope where we put in the stuff from the host
scope.SetVariable("lab", lab);

The object is the available in the script using the given name

lab.AnyMethodOfYourObject()


来源:https://stackoverflow.com/questions/2209226/ironpython-exposing-net-type-to-the-runtime-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!