我正在尝试使用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调用
发布于 2021-04-20 07:34:59
我认为您的问题是在import语句中使用了文件扩展名。
以下是对我有效的方法:
#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)
https://stackoverflow.com/questions/67122384
复制相似问题