Referencing hosting assembly in (Iron)Python script fails

4

I’m currently testing IronPython (I know a bit C# and a bit CPython). Now I want to use my custom class in a Python script.

I have the following project structure:

Solution IPTest
---Project IPTest
------Namespace IPTest
---------Program class (main)
---------Elem class
------Scripts
---------Worker.py

Where Elem is a simple:

public class Elem {
    public string Name;
}

I can use the Python scripts in the .NET program without any problems like:

ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("./Scripts/Worker.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
// or var worker = Python.CreateRuntime().UseFile("./Scripts/Worker.py");
dynamic Worker = scope.GetVariable("Worker");
dynamic worker = Worker();
var res1 = worker.add(4, 5);

However, I can’t figure out how to reference the hosting Assembly in the Python script. After some research I tried the following:

import sys
import System
sys.path.append(System.IO.Directory.GetCurrentDirectory()) #make sure assembly dir is  in sys.path
import clr
clr.AddReference(“IPTest.exe”)
# or clr.AddReferenceToFile(r"IPTest.exe")
# or clr.AddReference(r"<fullpath>\IPTest\bin\Debug\IPTest.exe")
# or clr.AddReference(“../IPTest.exe”) #when not adding workingdir to sys.path
from IPTest import Elem
# or from IPTest.IPTest import Elem
# or import Elem

Neither works. I get two different error messages:

  1. When adding workingdir to sys.path or using relative path or use AddReferenceToFile: No module named IPTest
  2. When using the absolute path: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

I checked that the Assembly name is really IPTest and tried to use a dll instead of exe - though it should usually not make any difference and surprisingly doesn’t work either.

disclaimer: The solution described here:

engine.Runtime.LoadAssembly(Assembly.GetExecutingAssembly()); //in c#
from IPTest import Elem # in python script

works just fine. However I think it should also work by referencing in the script file (which would be nicer).

Probably I’m missing something obvious, but I just can’t see it so any hint is much appreciated.

c#
ironpython
asked on Stack Overflow Sep 28, 2012 by marce • edited May 23, 2017 by Community

1 Answer

3

Try clr.AddReferenceToFile(r'IPTest.exe') as mentioned in your error:

  1. When adding workingdir to sys.path or using relative path or use AddReferenceToFile: No module named IPTest
answered on Stack Overflow Sep 28, 2012 by Mike Webb

User contributions licensed under CC BY-SA 3.0