在Python脚本中使用.Net (C#) dll
我正在尝试把一个简单的C#命令行工具移植到Python。这个C#程序使用了一个叫做foobar.dll的自定义.Net动态链接库,它通过I2C与一些实验室设备进行连接。在C#代码中使用这个dll的方式如下:
fooBar.fooProvider provider = new foobar.fooProvider()
fooBar.fooBarLib fooLib = new foobar.fooBarLib(provider, 0x80)
# used below ...
numFloat = fooLib.GetSomething()
# more python ...
fooLib.SetSomething(NumberAsAFloat)
我考虑过直接用ctypes来访问这个dll,但我觉得这可能不适用于C#/.Net。由于我们实验室的限制,我需要使用普通的Python版本加上额外的模块(也就是说,不使用IronPython或CPython)。我看过Python for .NET,但不确定这是否真的能用。我对.Net不太熟悉,但在Java、C++和Python方面有很多经验。有没有人遇到过这种情况,并找到好的解决方案呢?
编辑:
根据下面的解释,我在Python解释器中导入了clr,然后尝试导入fooBar库,结果如下:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Interop.AVMCIFCLib, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
File name: 'Interop.AVMCIFCLib, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null'
at System.Signature._GetSignature(SignatureStruct& signature, Void* pCorSig, Int32 cCorSig, IntPtr fieldHandle, IntPtr methodHandle, IntPtr declaringTypeHandle)
at System.Signature.GetSignature(SignatureStruct& signature, Void* pCorSig, Int32 cCorSig, RuntimeFieldHandle fieldHandle, RuntimeMethodHandle methodHandle, RuntimeTypeHandle declaringTypeHandle)
at System.Signature..ctor(RuntimeMethodHandle methodHandle, RuntimeTypeHandledeclaringTypeHandle)
at System.Reflection.RuntimeMethodInfo.get_Signature()
at System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()
at System.Reflection.RuntimeMethodInfo.GetParametersNoCopy()
at System.Reflection.RuntimePropertyInfo.GetIndexParameters()
at Python.Runtime.ClassManager.GetClassInfo(Type type)
at Python.Runtime.ClassManager.CreateClass(Type type)
at Python.Runtime.ClassManager.GetClass(Type type)
at Python.Runtime.ModuleObject.GetAttribute(String name, Boolean guess)
at Python.Runtime.ModuleObject.LoadNames()
at Python.Runtime.ImportHook.__import__(IntPtr self, IntPtr args, IntPtr kw)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
然后解释器崩溃了。这看起来像是一个构建得很糟糕的dll,对吧?
1 个回答
7
Python for .NET 这个工具非常好用,它可以让你在 Python 里面运行 .NET 的代码。IronPython 也很好用,不过它是反过来的。你可以把 Python for .NET 想象成是 CPython 的一个扩展,它能执行 .NET 的代码,而 IronPython 则是 CLR 的一个扩展,可以执行 Python 的代码。因为你需要使用普通的 Python,所以 Python for .NET 应该能满足你的需求。值得注意的是,普通的 Python 版本在大多数情况下就是指 CPython。