在(Iron)Python脚本中引用托管程序集失败

时间:2012-09-28 13:47:35

标签: c# ironpython

我正在测试IronPython(我知道有点C#和CPython)。现在我想在Python脚本中使用我的自定义类。

我有以下项目结构:

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

Elem很简单:

public class Elem {
    public string Name;
}

我可以在.NET程序中使用Python脚本而不会出现任何问题:

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);

但是,我无法弄清楚如何在Python脚本中引用托管程序集。经过一些研究后,我尝试了以下方法:

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

两者都不起作用。我收到两条不同的错误消息:

  1. 将workdir添加到sys.path或使用相对路径或使用时 AddReferenceToFile:没有名为IPTest的模块
  2. 使用绝对路径时:给定的程序集名称或代码库 无效。 (HRESULT异常:0x80131047)
  3. 我检查了程序集名称是否真的是IPTest,并尝试使用dll而不是exe - 虽然它通常不应该有任何区别,但令人惊讶的是也不起作用。

    免责声明:解决方案描述为here

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

    工作得很好。但是我认为它也应该通过脚本文件中的引用来工作(这会更好)。

    可能我错过了一些明显的东西,但我看不到它,所以任何提示都非常受欢迎。

1 个答案:

答案 0 :(得分:3)

按照错误中的说明尝试clr.AddReferenceToFile(r'IPTest.exe')

  1. 将workingdir添加到sys.path或使用相对路径或使用 AddReferenceToFile:没有名为IPTest的模块