【问题标题】:"No module named" error when attempting to importing c# dll using Python.NET尝试使用 Python.NET 导入 c# dll 时出现“未命名模块”错误
【发布时间】:2021-04-16 09:12:17
【问题描述】:

我正在尝试在 Anaconda 下使用 python.NET 将 c# 模块导入 Python

这已使用 pip install pythonnet 安装,报告“成功安装 pythonnet-2.5.2”

从那里使用 python 应该可以执行以下无法正常工作的操作。 Jetbrains dotPeek 可以看到该模块,并且对标准 Windows dll 的调用工作正常。 我做错了什么?

clr.AddReference(R'C:\Program Files (x86)\UVtools\UVtools.Core.dll')
from UVtools.Core import About
>>ModuleNotFoundError: No module named 'UVtools'
# never gets here:
print(About.Software)

这很好用:

import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Form
form = Form()
print(dir(form))
>> ['AcceptButton', ...

这也不起作用(尝试以不同的方式访问同一个 dll)

import System
uvTools = System.Reflection.Assembly.LoadFile(R'C:\Program Files (x86)\UVtools\UVtools.Core.dll')
print(uvTools.FullName)
print(uvTools.Location)
>>UVtools.Core, Version=2.8.4.0, Culture=neutral, PublicKeyToken=null
>>C:\Program Files (x86)\UVtools\UVtools.Core.dll
# But the following all fail with the same fundamental error:
print(uvTools.UVtools.Core.About)
print(uvTools.Core.About)
print(uvTools.About)
>>AttributeError: 'RuntimeAssembly' object has no attribute 'About'

JetBrains dotPeek 可以看到模块,这对我来说暗示这不是 dll 的问题。

我确实在其他地方看到,如果尝试使用 ctype,那么您需要在 c# 基本代码中包含“[DllExport("add", CallingConvention = CallingConvention.Cdecl)]",但我认为这不适用于 python。 NET clr 调用

【问题讨论】:

    标签: dllimport python.net


    【解决方案1】:

    我相信您的问题是您在导入语句中使用了文件扩展名。

    这对我有用:

    #add the directory the assembly is located in to sys.path.
    assembly_path1 = r"C:\DesktopGym\src\MouseSimulatorGui\bin\Debug"
    import sys
    sys.path.append(assembly_path1)
    
    import clr
    #add a reference to the assembly, by name without the .dll extension.
    clr.AddReference("GymSharp")
    
    #import the class. Here this is a public class, not static.
    from GymSharp import TicTacToeSharpEnvironment
    
    # instantiate a new instance
    env = TicTacToeSharpEnvironment()
    
    # call a method
    result = env.HelloWorld()
    
    print (result)
    

    在 C# 中,GymSharp 是名称空间,TicTacToeSharpEnvironment 是公共类的名称:

    namespace GymSharp
    {
        public class TicTacToeSharpEnvironment
        {
            public string HelloWorld()
            {
                return "Hello World";
            }
        }
    }
    

    我还用静态方法测试了我的静态类,所以这不是问题。

    namespace GymSharp
    {
    
        public static class StaticFoo
        {
            public static string StaticHelloWorld => "Static hello World";
        }
    

    来自 Python

    from GymSharp import StaticFoo
    print (StaticFoo.StaticHelloWorld)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-22
      • 2019-07-01
      • 2021-04-12
      • 1970-01-01
      • 2021-12-06
      • 2012-08-27
      • 2012-08-08
      • 1970-01-01
      相关资源
      最近更新 更多