首页 > 解决方案 > Instantiate a .Net class from IronPython without boilerplate

问题描述

To use a class from the .Net host application in IronPython, you can do this:

import clr
clr.AddReference('MyApplication')
from MyApplication import MyClass

x = MyClass()

But how can I do it without the first 3 lines or perhaps somehow executing them in the host application before it runs the script?

标签: python-importironpython

解决方案


Microsoft.Scripting.Hosting(这是 IronPython 中使用的动态语言运行时的一部分)中,您有一个ScriptScope的概念,您可以在其上执行语句或源脚本。

这允许您在执行实际脚本之前在范围上执行样板。以下示例显示了基本思想:

var engine = Python.CreateEngine();
var scope = engine.CreateScope();

var boilerplateSourceText = @"import clr
clr.AddReference('MyApplication')
from MyApplication import MyClass
";

var boilerplateSource = engine.CreateScriptSourceFromString(boilerplateSourceText, SourceCodeKind.Statements);
boilerplateSource.Execute(scope);

var scriptSource = engine.CreateScriptSourceFromString("x = MyClass()", SourceCodeKind.Statements);
scriptSource.Execute(scope);

推荐阅读