Access host class from IronPython script
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",开发者_JAVA技巧 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.
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.
精彩评论