6

我在通过 Python for .NET 使用 Python 加载外部 dll 时遇到问题。我在stackoverflow和类似的之后尝试了不同的方法。我将尝试总结情况并描述我已完成的所有步骤。

我有一个名为例如Test.NET.dll 的dll。我检查了 dotPeek,点击它可以看到 x64 和 .NET Framework v4.5。在我的计算机上,我安装了 .Net Framework 4。

我还以不同的方式为 .NET 安装了 Python。我认为最好的方法是从该网站LINK下载 .whl 。我已经下载并安装了:pythonnet‑2.0.0.dev1‑cp27‑none‑win_amd64.whl。我可以想象它适用于 .NET 4.0,因为需要 Microsoft .NET Framework 4.0。

安装完所有内容后,我可以执行以下命令:

>>> import clr
>>> import System
>>> print System.Environmnet.Version
>>> print System.Environment.Version
4.0.30319.34209

这似乎工作。然后,我尝试加载我的 dll,输入以下命令:

>>> import clr
>>> dllpath= r'C:\Program Files\API\Test.NET'
>>> clr.AddReference(dllpath)

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    clr.AddReference(dllpath)
FileNotFoundException: Unable to find assembly 'C:\Program Files\API\Test.NET'.
   at Python.Runtime.CLRModule.AddReference(String name)

我也尝试在路径末尾添加“.dll”,但没有任何改变。然后,我还尝试了LINKLINKLINK等中描述的不同解决方案……不幸的是,它不起作用,我得到了不同的错误。我知道存在 IronPython,但我试图避免使用它。

谢谢你的帮助!

4

2 回答 2

1

这不是一个完整的答案,但对未来的读者有帮助: 在探测程序集异常被吞下时,你不应该相信不幸FileNotFoundException的是clr.AddReference(dllpath)

public static Assembly AddReference(string name)
{
    AssemblyManager.UpdatePath();
    Assembly assembly = null;
    assembly = AssemblyManager.LoadAssemblyPath(name);
    if (assembly == null)
    {
        assembly = AssemblyManager.LoadAssembly(name);
    }
    if (assembly == null)
    {
        string msg = String.Format("Unable to find assembly '{0}'.", name);
        throw new System.IO.FileNotFoundException(msg);
     }
     return assembly ;
}

AssemblyManager.LoadAssemblyPath吞下异常

try   { assembly = Assembly.LoadFrom(path); }
catch {}

AssemblyManager.LoadAssembly也吞下异常

try { assembly = Assembly.Load(name);}
catch (System.Exception e) {}

您可以在Assembly.LoadFromAssembly.Load中检查可能被吞下的异常列表,以找出可能的真正原因

于 2015-12-08T09:32:43.360 回答
1

Test.NET.dll 是否来自另一台计算机?根据这个线程,.NET 的一些安全功能可以防止 .dll 很好地加载。

有关更多信息的错误消息,请尝试

> from clr import System
> from System import Reflection
> full_filename = r'C:\Program Files\API\Test.NET'
> Reflection.Assembly.LoadFile(dllpath)

如果您收到类似以下内容的错误消息

NotSupportedException: An attempt was made to load an assembly from a 
network location which would have caused the assembly to be sandboxed in 
previous versions of the .NET Framework. This release of the .NET Framework 
does not enable CAS policy by default, so this load may be dangerous. If 
this load is not intended to sandbox the assembly, please enable the 
loadFromRemoteSources switch.

然后以下解决了我的问题:

  • 右键单击 Test.NET.dll
  • 选择“属性”
  • 在“常规”选项卡下,单击“取消阻止”
  • 点击“应用”
于 2015-11-13T00:02:32.787 回答