问题描述
我正在尝试在 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 调用
解决方法
我认为您的问题是您在导入语句中使用了文件扩展名。
这对我有用:
#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)