5

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.

Max
  • 19,654
  • 13
  • 84
  • 122

1 Answers1

3

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.

Cameron
  • 96,106
  • 25
  • 196
  • 225
  • I can import a class from an external assembly. But I need to use a class from the hosting assembly. The one that starts the python script. I've tried to play with import, but couldn't find a way to do this. – Max Jun 04 '11 at 09:25
  • @Max: The hosting assembly is not special in any way -- you'll need to import from it just as you would from any other assembly. You can put the full, absolute path to its DLL in the `AddReference()` call -- if that works, then you know it's just a path/current directory issue (which can be annoying, but at least you'll know if the code works or not) – Cameron Jun 04 '11 at 14:02
  • Since the script was being hosted I was sure that I do not need to import the hosting assembly. And now that I've tried I see it's working. It is strange though that when I passed the class instance and queried class name and module it seemed like the class is already a part of a global namespace. – Max Jun 04 '11 at 19:39