I have this python code:
import ctypes
lib = ctypes.CDLL('/home/pi/serial_communication/crc.so')
C=0
def spi_process(gpio,level,tick):
print("Detected")
data = [0]*1024
with open(output_file_path(), 'w') as f:
for x in range(1):
spi.xfer2(data)
values = struct.unpack("<" "I"*256, bytes(data))
C = lib.crc32Word(0xffffffff,data,1024)
f.write("\n")
f.write("\n".join([str(x) for x in values]))
print(C)
input("Press Enter to start the process ")
cb1=pi.callback(INTERRUPT_GPIO, pigpio.RISING_EDGE, spi_process)
while True:
lib.crc32Word.restype=ctypes.c_int
lib.crc32Word.argtypes=[ctypes.c_int, ctypes.POINTER(ctypes.c_void_p), ctypes.c_int]
time.sleep(1)
But when I run it, I receive this error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_innerself.run()
File "/usr/lib/python3/dist-packages/pigpio.py", line 1213, in run cb.func(cb.gpio, newLevel, tick)
File "2crc_spi.py", line 47, in spi_process
C=lib.crc32Word(0xffffffff,data,1024)
ctypes.ArgumentError: argument 2: <class 'TypeError'>: LP_c_long instance instead of list
I am trying to call this C function from a c library:
uint32_t crc32Word(uint32_t crc, const void *buffer, uint32_t size)
Can someone please help? Thanks.
CodePudding user response:
The problem can be reduced to the following code. The 2nd parameter was incorrect as ctypes.POINTER(ctypes.c_void_p)
would be used for C void**
not void*
. The other parameters were using signed vs. unsigned types so that has been corrected as well. The data
must be either bytes
or a ctypes
array such as (c_uint8 * 1024)()
to be suitable for c_void_p
.
lib = ctypes.CDLL('/home/pi/serial_communication/crc.so')
lib.crc32Word.argtypes = ctypes.c_uint32, ctypes.c_void_p, ctypes.c_uint32
lib.crc32Word.restype = ctypes.c_uint32
data = bytes([0] * 1024)
crc = lib.crc32Word(0xffffffff, data, len(data))