Instantiating custom C# classes from IronPython
Asked Answered
F

1

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!

Fin answered 3/6, 2012 at 13:55 Comment(0)
O
8

Assuming MyClass is in MyAssembly.dll:

import clr
clr.AddReference('MyAssembly.dll')
import MyClass
obj = MyClass("Hello, World!")
obj.Write()
Occasional answered 3/6, 2012 at 14:10 Comment(3)
Thanks! I'll have to do some magic to make it work but it will :)Fin
For me works as clr.AddReference('MyAssembly') - without .dllDario
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/…Galloon

© 2022 - 2024 — McMap. All rights reserved.