Python Forum
Issue while using ctypes in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issue while using ctypes in python
#1
I have the below python script which I am using to collect data from a microcontroller using SPI communication. That part is working fine, however, now I am trying to implement CRC function from a c file.
import ctypes
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

INTERRUPT_GPIO=12
pi.set_mode(INTERRUPT_GPIO, pigpio.INPUT)
C=0
 
def output_file_path(): return os.path.join(os.path.dirname(__file__), datetime.datetime.now().strftime("%dT%H.%M.%S") + ".csv")
 
def spi_process(gpio,level,tick):
    data = [0]*1024
    spi.xfer([0x02])
    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,len(data))
            f.write("\n")
            f.write("\n".join([str(x) for x in values]))
        print(C)

cb1=pi.callback(INTERRUPT_GPIO, pigpio.RISING_EDGE, spi_process)

while True:
    time.sleep(1)
The C function that I am trying to invoke from the python script is
crc32Word(uint32_t crc, const void *buffer, uint32_t size)
But when I run the above script, I receive error as:
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 50, in spi_process
    C=lib.crc32Word(0xffffffff,data,len(data))
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type
One way to solve this is to use data = bytes([0]*1024). But if I use this method, the file stores 0s even if I am actually receiving data correctly (checked using logic analyzer).

Can someone please help? Thanks.
Reply
#2
Use array instead of lists.
Reply
#3
(Mar-01-2022, 04:42 AM)deanhystad Wrote: Use array instead of lists.
Hi deanhystad,
Thanks for the reply. When I create list using numpy library and change line where I initialize "data", I get below error:
import numpy as np

#changed initialization of data to:
data= np.arange(1024) #also tried: np.zeros(1024,ctypes.c_uint8), also get same error
Error:
File "2crc_spi.py", line 48, in spi_process
   spi.xfer2(data)
TypeError: Non-Int/Long value in arguments: b5410b00
But spi only transfers a byte at a time, not sure why it says non-int value. Any suggestion for this?
Reply
#4
I was thinking the array library, not numpy.
Reply
#5
bytes is immutable. That is why data doesn't change when you made it: data = bytes([0]*1024). It is like passing a string and expecting the c function to modify the python string.

bytearray is a mutable sequence. You could try data = bytearray([0]*1024).
GiggsB likes this post
Reply
#6
(Mar-01-2022, 08:07 PM)deanhystad Wrote: bytes is immutable. That is why data doesn't change when you made it: data = bytes([0]*1024). It is like passing a string and expecting the c function to modify the python string.

bytearray is a mutable sequence. You could try data = bytearray([0]*1024).
Got it. I will try this and see if this works.
Reply
#7
Hi,

I just wanted to give an update (I wasn't able to work on this issue for some time) that I was able to solve the issues. I used a python library called zlib instead of calling a C function. Using a python library looked easier. I also worked using @deanhystad's suggestion that data was actually immutable. So, I was able to update my python script accordingly and was able to make it work. I am adding my code just in case someone else faces similar issue.
import datetime
import os
import struct
import time
import pigpio
import spidev
import zlib

INTERRUPT_GPIO=25

bus = 0
device = 0
spi = spidev.SpiDev()
spi.open(bus, device)
spi.max_speed_hz = 4000000
spi.mode = 0

pi = pigpio.pi()
if not pi.connected:
    exit()

pi.set_mode(INTERRUPT_GPIO, pigpio.INPUT)

C=0
 
def output_file_path():
    return os.path.join(os.path.dirname(__file__),
               datetime.datetime.now().strftime("%dT%H.%M.%S") + ".csv")
 
def spi_process(gpio,level,tick):
    print("Detected")
    data = bytes([0]*1024)
    spi.xfer2([0x02])
    with open(output_file_path(), 'w') as f:
        t1=datetime.datetime.now()
        for x in range(1):
            recv = spi.xfer2(data)
            values = struct.unpack("<" +"I"*256, bytes(recv))
            C = zlib.crc32(bytes(recv))
            f.write("\n")
            f.write("\n".join([str(x) for x in values]))
        t2=datetime.datetime.now()
        print(t2-t1)
        print(C)

input("Press Enter to start the process ")
spi.xfer2([0x01])

cb1=pi.callback(INTERRUPT_GPIO, pigpio.RISING_EDGE, spi_process)

while True:
    time.sleep(1)
Thank you so much for all your help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  using ctypes to use a dll in a python module dauriac 3 387 Mar-06-2024, 04:38 PM
Last Post: dauriac
  Trying to debug segfault in ctypes binding to Fortran bthomas 1 607 Sep-01-2023, 11:26 AM
Last Post: bthomas
  ctypes juliolop 7 1,402 Apr-20-2023, 03:33 PM
Last Post: Larz60+
  Ctypes and libffi.so.7 luxedo 1 6,062 Oct-23-2021, 09:24 PM
Last Post: DeaD_EyE
  possible ctypes and numpy conflict? herbal_rage 0 3,153 Apr-16-2020, 11:35 AM
Last Post: herbal_rage
  python kernell crash with a ctypes program Jstechg 1 3,500 Nov-24-2018, 02:37 PM
Last Post: Jstechg
  generating ctypes wrapper for a c library? brighteningeyes 9 7,082 Nov-04-2018, 02:31 AM
Last Post: brighteningeyes
  DLL library with ctypes Max20 0 2,912 Aug-19-2018, 11:15 AM
Last Post: Max20
  dll not loading to Ctypes Philbot 1 6,861 Jul-01-2018, 09:55 AM
Last Post: Philbot
  Error Ctypes in Windows rramosg 4 9,369 Oct-17-2017, 05:26 AM
Last Post: rramosg

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020