Host class access from IronPython script

How do I access a C # class from an IronPython script? WITH#:

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 the classes defined in the hosting assembly.

+5
source share
1 answer

You have installed tin the instance MyClass, but you are trying to use it as if it were the class itself.

You need to either import MyClassfrom your IronPython script, or introduce some kind of factory method (since classes are not first-class objects in C #, you cannot pass in MyClass). Alternatively, you can go through typeof(MyClass)and use System.Activator.CreateInstance(theMyClassTypeObject)for a new instance.

MyEnum ( , script - , ), :

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

, script ( , File ) script clr.AddReference().

+3

All Articles