在Python脚本中使用.net (c#) dll

本文关键字:dll net Python 脚本 | 更新日期: 2023-09-27 17:53:06

我正在尝试将一个简单的c#命令行实用程序移植到Python。c#程序使用一个名为foobar.dll的自定义. net dll,它通过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。)我研究了。net的Python,但我不确定这是否真的有效。我对。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,对吗?

在Python脚本中使用.net (c#) dll

. net的Python 工作得非常好,您可以在Python中执行。net代码。IronPython也能很好地工作,尽管相反。你可以把。net版本的Python看作是可以执行。net代码的CPython的扩展,而IronPython是允许执行Python代码的CLR的扩展。由于您的需求要求您使用普通的Python,因此。net版本的Python应该可以工作。需要注意的是,一般的python发行版在大多数情况下是 CPython。