在Python脚本中使用.Net(C#)dll

chi*_*ete 5 .net c# python dll python.net

我正在尝试将一个简单的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)
Run Code Online (Sandbox Code Playgroud)

我想过简单地使用ctypes访问dll,但我认为这对C#/ .Net不起作用.由于我们实验室的限制,我需要使用一个vanilla Python发行版+插件模块(即不是IronPython或CPython.)我看了Python for .NET,但我不确定这实际上是否有用.我是.Net的n00b,但在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].
Run Code Online (Sandbox Code Playgroud)

然后解释器崩溃了.这看起来像一个糟糕的DLL,对吗?

Can*_*cer 7

Python for .NET运行良好,您可以在Python中执行.NET代码.IronPython也运作良好,但另一种方式.您可以将Python for .NET视为可以执行.NET代码的CPython的扩展,而IronPython是允许执行Python代码的CLR的扩展.由于您的需求要求您使用vanilla Python,因此Python for .NET应该可行.值得注意的是,在大多数情况下,vanilla python发行版都是 CPython.