4

我目前正在测试 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. 将 workingdir 添加到 sys.path 或使用相对路径或使用 AddReferenceToFile 时:没有名为 IPTest 的模块
  2. 使用绝对路径时:给定的程序集名称或代码库无效。(来自 HRESULT 的异常:0x80131047)

我检查了程序集名称是否真的是 IPTest 并尝试使用 dll 而不是 exe - 尽管它通常应该没有任何区别,而且令人惊讶的是也不起作用。

免责声明:此处描述的解决方案:

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

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

可能我遗漏了一些明显的东西,但我只是看不到它,所以非常感谢任何提示。

4

1 回答 1

3

clr.AddReferenceToFile(r'IPTest.exe')按照您的错误中所述尝试:

  1. 将 workingdir 添加到 sys.path 或使用相对路径或使用AddReferenceToFile 时:没有名为 IPTest 的模块
于 2012-09-28T16:23:44.040 回答