使用pythonnet在Python中调用C# DLL遇‘No module named 'test'’错误求助
解决Python调用C# DLL时的“No module named 'test'”错误
问题重现
运行Python代码时始终报错:No module named 'test',相关代码与环境信息如下:
Python代码
from clr_loader import get_coreclr from pythonnet import set_runtime rt = get_coreclr(runtime_config="C:\\Users\\Batman\\source\\repos\\BlazorApp1\\PythonTest\\runtimeconfig.json") set_runtime(rt) import clr import sys sys.path.append("C:/Users/Batman/source/repos/BlazorApp1/TestLibrary/bin/Debug/net6.0") test = sys.path clr.AddReference("TestLibrary") from test import TestClass sayTest()
C#代码
using System.Runtime.InteropServices; namespace test { [ComVisible(true)] public class TestClass { public void sayTest() { Console.WriteLine("TEST"); } } }
文件路径与环境信息
- 项目根路径:
C:\Users\Batman\source\repos\BlazorApp1 - Python文件位置:
PythonTest目录 - C#文件位置:
TestLibrary目录 - DLL路径:
C:\Users\Batman\source\repos\BlazorApp1\TestLibrary\bin\Debug\net6.0\TestLibrary.dll - Python版本:3.10 64位
- Pythonnet版本:3.0.2
- .NET版本:6.0.0
- runtimeconfig.json内容:
{ "runtimeOptions": { "tfm": "netcoreapp6.0", "framework": { "name": "Microsoft.NETCore.App", "version": "6.0.0" } } }
错误原因与修复方案
核心问题1:变量名冲突
Python代码里将sys.path赋值给了test变量,直接覆盖了C#的test命名空间,导致Python无法识别该命名空间。
核心问题2:方法调用错误
sayTest()是TestClass的实例方法,不能直接调用,必须先创建类的实例再调用方法。
修复后的Python代码
from clr_loader import get_coreclr from pythonnet import set_runtime rt = get_coreclr(runtime_config="C:\\Users\\Batman\\source\\repos\\BlazorApp1\\PythonTest\\runtimeconfig.json") set_runtime(rt) import clr import sys # 添加DLL所在目录到路径 sys.path.append("C:/Users/Batman/source/repos/BlazorApp1/TestLibrary/bin/Debug/net6.0") # 移除覆盖命名空间的变量赋值 clr.AddReference("TestLibrary") # 正确导入C#命名空间下的类 from test import TestClass # 创建类实例并调用方法 test_instance = TestClass() test_instance.sayTest()
额外注意事项
- 确保
TestLibrary.dll已成功编译,路径完全正确 - 确认Python和.NET的位数一致(当前均为64位,符合要求)
- 检查
runtimeconfig.json的框架版本与本地安装的.NET 6.0.0匹配
内容的提问来源于stack exchange,提问作者freyfrey01
相关产品推荐
相关产品推荐

