调用c++库时,如何在Python中使用ctypes传递字节作为引用

How do I pass a byte as reference in Python using ctypes when calling a c++ library?

本文关键字:ctypes 字节 引用 库时 c++ Python 调用      更新时间:2023-10-16

我一直在想如何将一些c++函数导入python。我让它们工作,直到其中一个函数需要通过引用传递它的一个属性,我不知道如何使它工作。我一直在遵循这里给出的建议:https://stackoverflow.com/a/252473/7447849它一直工作得很好,直到我尝试了这个:

我有以下c++功能:

bool __stdcall I2CRead(int Instance,  BYTE SlaveAddress, BYTE registerAddress, BYTE* ReadBuff, BYTE Length)

这是我尝试过的代码:

i2cread_proto = ctypes.WINFUNCTYPE (ctypes.c_bool, ctypes.c_int, ctypes.c_byte, ctypes.c_byte, ctypes.c_byte, ctypes.c_byte)
i2cread_Params = (1, "instance", 0),(1, "SlaveAddress", 0),(1, "registerAddress", 0),(1, "ReadBuff", 0),(1, "Length", 0), # (parameter direction (1 for input, 2 for output), parameter name, default value)
i2cread = i2cread_proto (("I2CRead", qsfp_lib), i2cread_Params)
readBuff = ctypes.c_byte(0)
if (i2cread(0, 160, address, readBuff, 1)==True):
print(readBuff)
else:
print('Could not read data')

此代码有效,但readBuff保持给定的默认值不变,而不是按原样更改。

我尝试使用byref((,但仍然无法工作(它给了我一个错误的类型错误(。

我可能做错了什么?我对Python不太熟练,所以可能有一个概念我误解了

未测试。请确保使用正确的参数类型。

from ctypes import *
dll = WinDLL('dllname')
dll.I2CRead.argtypes = c_int,c_ubyte,c_ubyte,POINTER(c_ubyte),c_ubyte
dll.I2CRead.restype = c_bool
output = (c_ubyte * 256)()  # Create instance of a c_ubyte array to store the output.
result = dll.I2CRead(1,2,3,output,len(output))