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

2024-04-29 05:35:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一个简单的C#命令行实用程序移植到Python。C#程序使用名为foobar.dll的自定义.Net dll,该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)。我是N900B到.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,对吗?


Tags: theassemblysystematruntimefoobardllsignature
1条回答
网友
1楼 · 发布于 2024-04-29 05:35:45

Python for .NET工作得非常好,您可以在Python中执行.NET代码。IronPython也工作得很好,尽管相反。您可以将Python for.NET看作是可以执行.NET代码的CPython的扩展,而IronPython是允许执行Python代码的CLR的扩展。因为您的需求要求您使用普通的Python,所以Python for.NET应该可以工作。需要注意的是,普通的python发行版在大多数情况下都是CPython。

相关问题 更多 >