将字节作为参数传递给c#?

2024-05-13 07:07:36 发布

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

我目前在尝试从python调用c#方法时遇到了问题。我使用的是python3.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时遇到了一些重大问题。一点也不跑。但是在这个确切的配置中它似乎可以工作(我需要将路径保存到一个变量,否则它就不能工作了,我也不能输入dll的路径clr.AddReference(路径)因为这不起作用)

c#version方法如下所示:

^{pr2}$

My status变量获取一个与c类的status enum完美配合的值。在

问题是:调用后我的变量“version”为空。为什么?根据:How to use a .NET method which modifies in place in Python?这应该是一种合法的做事方式。我也尝试使用显式版本,但我的命名空间clr不包含清除引用(). 在

下一个(也是更严重的)问题是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

希望你们中有人知道如何解决这个问题。在

谢谢, 凯文


Tags: pathinpyadaptergpioversionstatusline
1条回答
网友
1楼 · 发布于 2024-05-13 07:07:36

在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]

相关问题 更多 >