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.
You’ve set
tto an instance ofMyClass, but you’re trying to use it as if it were the class itself.You’ll need to either import
MyClassfrom within your IronPython script, or inject some sort of factory method (since classes aren’t first-class objects in C#, you can’t pass inMyClassdirectly). Alternatively, you could pass intypeof(MyClass)and useSystem.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:You might have to play around with the script source type (I think
Fileworks best) and the script execution path to get theclr.AddReference()call to succeed.