1
votes

I'm using IronPython to execute a python script from my C# application. I want the script to access my C# classes in addition to some System classes for creating a form from the script. The following is the importing done within the python script:

import clr
clr.AddReference('MyApp')

from MyApp import MyClass

I execute the script from C# as follows:

ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile(Directory.GetCurrentDirectory()+"/python/test.py", scope);

The program fails on this line of my script, returning "Cannot import name MyClass":

from MyApp import MyClass

My file hierarchy looks like this:

root folder
    -MyApp.exe
    -python
        -test.py

The program has no trouble adding the reference to my .exe file, but it won't load the class. What's more baffling is that this works:

import MyApp

Is the above line importing my namespace, also named "MyApp", from my assembly, "MyApp"? I tried removing MyClass from the namespace MyApp, but that changed nothing. I tried building MyApp as a .dll and inserting it both in root directory and in the script directory, but nothing has worked, even after long hours of scouring the internet.

Why can't IronPython locate MyClass? Why does it successfully import MyApp from MyApp, and what is it actually doing when that happens?

MyClass.cs:

// Omitted "using" statements

namespace MyApp{
    class MyClass{
        public static void MethodIWantToUse(){}
    }
}
1

1 Answers

0
votes

Through some more research, I managed to find this article which helped me solve my problem: Accessing C# class members in IronPython

MyClass was defined with the implicit default "internal" visibility, so it wasn't visible to the python script outside my assembly. Changing visiblity of MyClass to "public" like so:

namespace MyApp{
    public class MyClass{
        public static void MethodIWantToUse(){}
    }
}

...allowed me to import the class into my python script by typing:

from MyApp import MyClass

Thus importing MyClass from the namespace MyApp, which is contained in the MyApp assembly.

(I also learned that "import MyApp" was importing the namespace MyApp from my assembly, which happened to have the same name.)