c# - 从 IronPython 脚本访问主机类

标签 c# ironpython

如何从 IronPython 脚本访问 C# 类? C#:

public class MyClass
{
}

public enum MyEnum
{
    One, Two
}

var engine = Python.CreateEngine(options);
var scope = engine.CreateScope();
scope.SetVariable("t", new MyClass());
var src = engine.CreateScriptSourceFromFile(...);
src.Execute(scope);

IronPython 脚本:

class_name = type(t).__name__     # MyClass
class_module = type(t).__module__ # __builtin__

# So this supposed to work ...
mc = MyClass() # ???
me = MyEnum.One # ???

# ... but it doesn't

更新

我需要导入在托管程序集中定义的类。

最佳答案

您已将 t 设置为 MyClass 的一个实例,但您正试图将它当作类本身来使用.

您需要从 IronPython 脚本中导入 MyClass,或者注入(inject)某种工厂方法(因为类不是 C# 中的一流对象,您不能传入MyClass 直接)。或者,您可以传入 typeof(MyClass) 并使用 System.Activator.CreateInstance(theMyClassTypeObject) 来新建一个实例。

由于您还需要访问 MyEnum(注意您在脚本中使用它而没有提及它可能来自哪里),我建议只使用导入:

import clr
clr.AddReference('YourAssemblyName')

from YourAssemblyName.WhateverNamespace import MyClass, MyEnum

# Now these should work, since the objects have been properly imported
mc = MyClass()
me = MyEnum.One

您可能需要尝试使用脚本源类型(我认为 File 效果最好)和脚本执行路径来获取 clr.AddReference() 调用成功。

关于c# - 从 IronPython 脚本访问主机类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6234355/

相关文章:

c# - 您如何为您的对象实现审计跟踪(编程)?

python - 无法将 numpy 导入嵌入式 ironpython 引擎

c# - 更改 web.config 会导致 IIS 网站刷新,是否还会再次触发运行静态构造函数?

c# - 使用 sharpsvn 驱动程序进行颠覆认证

C# 到 VB.Net : Why does this fail to compile when converted to VB?

ubuntu - 在 PyCharm IDE 中的 Mono 上使用 IronPython

c#-4.0 - 将静态方法添加到 IronPython 范围

Python - IronPython 困境

python - IronPython - sys.exit() 上的正确资源释放

c# - 绑定(bind) IsEnabled 不起作用