Link to hosting assembly in (Iron) Python script not working

Im currently testing IronPython (I know a bit of C # and a bit of CPython). Now I want to use my own 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 Simple:

 public class Elem { public string Name; } 

I can use Python scripts in a .NET program without any problems, for example:

 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 cannot figure out how to reference the hosting assembly in a 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 

Nothing works. I get two different error messages:

  • When adding workdir to sys.path or using a relative path or using AddReferenceToFile: there is no module named IPTest
  • When using an absolute path: the given assembly name or code base is invalid. (Exception from HRESULT: 0x80131047)

I checked that the assembly name is really IPTest and is trying to use dll instead of exe - although this usually doesnโ€™t 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 work as well, referencing in a script file (which would be better).

I might have missed something obvious, but I just can't see it, so any hint is really appreciated.

+4
source share
1 answer

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

  • When adding workdir to sys.path or using a relative path or using AddReferenceToFile: There is no module named IPTest
+3
source

Source: https://habr.com/ru/post/1436820/


All Articles