Access host class from IronPython script

这一生的挚爱 提交于 2020-01-03 11:32:20

问题


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 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

UPDATE

I need to import classes defined in a hosting assembly.


回答1:


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

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.

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

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.



来源:https://stackoverflow.com/questions/6234355/access-host-class-from-ironpython-script

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