Pythonnet:无法访问 dll 类

时间:2021-07-07 16:24:31

标签: python.net

我在尝试使用 pythonnet 加载在 c# 中创建的 Dll 类时遇到问题

这是 dll 项目配置(VS)

enter image description here

这是课程代码

using System;

namespace ClassLibrary1
{
    public class Class1{   
        public void test()
        {
            Console.WriteLine("Hello from a library");
        }
    }
}

这是dll信息

enter image description here

还有剧本

import clr
clr.AddReference('ClassLibraryAss')
from ClassLibraryAss import Class1
x = Class1()
x.test()

能够找到程序集。我遵循了一些例子,没有比这更难的了。

这是输出

Traceback (most recent call last):
  File ".\testDLL.py", line 23, in <module>
    from ClassLibraryAss import Class1
ModuleNotFoundError: No module named 'ClassLibraryAss'

我尝试了不同的方法来加载模块,但没有成功

环境

  • Pythonnet 版本:2.5.2(也试过 2.5.1)
  • Python 版本:3.8.0
  • 操作系统:Windows 10
  • Visual Studio 2019(其他我没试过)

2 个答案:

答案 0 :(得分:0)

在您的 from XXX import Class1 中,XXX 应该是 Class1 所在的命名空间,而不是 DLL 名称

答案 1 :(得分:0)

事实证明 dll 是在 .net core 中制作的,默认情况下 pythonnet 不能使用它。

Acording to the issue

所以使用 .net 框架制作 dll 是可行的。在问题中说一种使用 net core dll 运行它的方法,但我没有尝试

import clr
#I made a dll with .net Framework 4.8 called ClassLibraryNetF 
from ClassLibraryNetF import Class1

x = Class1()
x.test()