6

Is there any way to make a class available to IronPython scripts so that I can create objects inside the code?

For example, if I have a class that I want to be able to instantiate from the script called MyClass defined in the C# code like so:

public class MyClass
{
    string text;

    public MyClass(string text)
    {
        this.text = text;
    }

    public void Write()
    {
        Console.WriteLine(text);
    }
}

How can I do this in the Python script?

obj = MyClass("Hello, World!")
obj.Write()

Thanks!

jmegaffin
  • 1,162
  • 11
  • 22

1 Answers1

8

Assuming MyClass is in MyAssembly.dll:

import clr
clr.AddReference('MyAssembly.dll')
import MyClass
obj = MyClass("Hello, World!")
obj.Write()
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • Thanks! I'll have to do some magic to make it work but it will :) – jmegaffin Jun 03 '12 at 14:20
  • 1
    For me works as `clr.AddReference('MyAssembly')` - without `.dll` – Dzmitry Paliakou Jan 24 '19 at 17:18
  • AddReference didn't work for me but AddReferenceToFileAndPath did (I used absolute paths). If have an **exe** then check our this page **how to build a dll**: https://learn.microsoft.com/en-us/dotnet/core/tutorials/library-with-visual-studio – Seabass77 Jul 11 '19 at 15:04