从IronPython的脚本访问主机类 [英] Access host class from IronPython script

查看:168
本文介绍了从IronPython的脚本访问主机类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I access a C# class from IronPython script? 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的脚本:

IronPython script:

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



更新

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

I need to import classes defined in a hosting assembly.

推荐答案

您已经设置 T 实例 MyClass的>,但你想使用它,好像它是类本身。

You've set t to an instance of MyClass, but you're trying to use it as if it were the class itself.

您需要的将是进口 MyClass的从IronPython的脚本中,或注射某种工厂方法(因为类在C#中没有第一类对象,你不能在 MyClass的直接)。或者,你可以在传递的typeof(MyClass的),并使用 System.Activator.CreateInstance(theMyClassTypeObject)来新建立一个实例。

You'll need to either import MyClass from within your IronPython script, or inject some sort of factory method (since classes aren't first-class objects in C#, you can't pass in MyClass directly). Alternatively, you could pass in typeof(MyClass) and use System.Activator.CreateInstance(theMyClassTypeObject) to new up an instance.

既然你也需要访问 MyEnum (注意,你使用它在脚本中没有任何参考到它可能来自),我建议只使用进口的:

Since you also need to access MyEnum (note you're using it in your script without any reference to where it might come from), I suggest just using imports:

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

您可能不得不玩的脚本源类型(我想文件效果最好)和脚本执行路径,以获得 clr.AddReference()调用成功。

You might have to play around with the script source type (I think File works best) and the script execution path to get the clr.AddReference() call to succeed.

这篇关于从IronPython的脚本访问主机类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆