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!

1 Answer 1

8

Assuming MyClass is in MyAssembly.dll:

import clr
clr.AddReference('MyAssembly.dll')
import MyClass
obj = MyClass("Hello, World!")
obj.Write()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I'll have to do some magic to make it work but it will :)
For me works as clr.AddReference('MyAssembly') - without .dll
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: learn.microsoft.com/en-us/dotnet/core/tutorials/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.