我目前在尝试从 python 调用 c# 方法时卡住了。我使用的是 python 3.2 而不是 IronPython。我用pip安装了最新版的python.net
使用 ref 或 out 参数时出现问题(正如经常讨论的那样)。
到目前为止,这是我的代码:
import clr
path = clr.FindAssembly("USB_Adapter_Driver")
clr.AddReference(path)
from USB_Adapter_Driver import USB_Adapter
gpio = USB_Adapter()
version2 = ''
status, version = gpio.version(version2)
print ('status: ' + str(status))
print ('Version: ' + str(version))
readMask = bytearray([1])
writeData = bytearray([0])
print (readMask)
print (writeData)
status, readData = gpio.gpioReadWrite(b'\x01',b'\x00',b'\x00')
status, readData = gpio.gpioReadWrite(readMask[0],writeData[0],b'\x00')
status, readData = gpio.gpioReadWrite(readMask[0],writeData[0],)
我在获取 clr 时遇到了一些重大问题。在所有运行。但是在这个确切的配置中它似乎工作(我需要保存变量的路径,否则它不会工作,我也不能在 clr.AddReference(path) 中键入 dll 的路径,因为这也不会工作)
c# 版本方法如下所示:
public USB_Adapter_Driver.USB_Adapter.Status version(ref string ver)
我的状态变量获得了一个与 c# 类的状态枚举完美配合的值。
问题是:调用后我的变量“version”为空。为什么?根据:How to use a .NET method which modifies in place in Python?这应该是一种合法的做事方式。我还尝试使用显式版本,但我的命名空间 clr 不包含 clr.Reference()。
下一个(也是更严重的)问题是 pio.gpioReadWrite()。这里是关于这个问题的信息:
public USB_Adapter_Driver.USB_Adapter.Status gpioReadWrite(byte readMask, byte writeData, ref byte readData)
这里我得到错误信息:
TypeError: No method matches given arguments
我使用上面的哪个调用并不重要。所有这些都失败了。
这是调试运行的完整输出:
d:\[project path]\tests.py(6)<module>()
status: 6
Version:
bytearray(b'\x01')
bytearray(b'\x00')
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
d:\[project path]\tests.py(28)<module>()
status, readData = gpio.gpioReadWrite(readMask[0],writeData[0],)
(Pdb) Traceback (most recent call last):
File "D:\WinPython-64bit-3.4.4.2Qt5\python-3.4.4.amd64\lib\pdb.py", line 1661, in main
pdb._runscript(mainpyfile)
File "D:\WinPython-64bit-3.4.4.2Qt5\python-3.4.4.amd64\lib\pdb.py", line 1542, in _runscript
self.run(statement)
File "D:\WinPython-64bit-3.4.4.2Qt5\python-3.4.4.amd64\lib\bdb.py", line 431, in run
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "d:\[project path]\tests.py", line 28, in <module>
status, readData = gpio.gpioReadWrite(readMask[0],writeData[0],)
TypeError: No method matches given arguments
希望你们中有人知道如何解决这个问题。
谢谢, 凯文
最佳答案
Python.Net 不像 IronPython 那样处理 ref/out 参数。
status, readData = gpio.gpioReadWrite(b'\x01',b'\x00',b'\x00')
调用不太正确,因为 Python.Net 不会返回更新的 readData 作为第二个结果。
您可以使用反射处理 ref 参数。查看我对类似问题的回答here
针对您的情况有一个粗略的代码模板:
import clr
clr.AddReference("USB_Adapter_Driver")
import System
import USB_Adapter_Driver
myClassType = System.Type.GetType("USB_Adapter_Driver.USB_Adapter, USB_Adapter_Driver")
method = myClassType.GetMethod("gpioReadWrite")
parameters = System.Array[System.Object]([System.Byte(1),System.Byte(0),System.Byte(0)])
gpio = USB_Adapter_Driver.USB_Adapter()
status = method.Invoke(gpio,parameters)
readData = parameters[2]
关于c# - 将字节作为参数传递给 c#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37789281/