ctypes

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 30 02:29:54 CEST 2009


En Wed, 29 Apr 2009 05:05:52 -0300, luca72 <lucaberto at libero.it> escribió:

> can you explain how to use this function :
> this is the api documentation :
> PREF0 short usb_tc08_get_single (
>   short   handle,
>   float * temp,
>   short * overflow_flags,
>   short   units);
>
> This is the sample made in c:
> int main(void)
> {
>         short handle = 0;     /* The handle to a TC-08 returned by
> usb_tc08_open_unit() */
>         char selection = 0;   /* User selection from teh main menu */
>         float temp[9];        /* Buffer to store temperature readings
> from
> the TC-08 */
>         int channel, reading; /* Loop counters */
>         int retVal = 0;       /* Return value from driver calls
> indication
> success / error */
>         USBTC08_INFO unitInfo;/* Struct to hold unit information */
>
> usb_tc08_get_single(handle, temp, NULL, USBTC08_UNITS_CENTIGRADE);

> i do
> strumento = ctypes.cdll.LoadLibrary('/home/luca/Desktop/luca/
> progetti_eric/Pico/libusbtc08-1.7.2/src/.libs/libusbtc08.so')
> strumento.usb_tc08_get_single.argtypes = [ctypes.c_short,
> ctypes.c_float, ctypes.c_short, ctypes.c_short] is this correct?

That's wrong. Second and third parameters are pointers:

# define a pointer type
c_float_p = ctypes.POINTER(ctypes.c_float)
c_short_p = ctypes.POINTER(ctypes.c_short)

usb_tc08_get_single = strumento.usb_tc08_get_single
usb_tc08_get_single.argtypes = [
   ctypes.c_short,
   c_float_p,
   c_short_p,
   ctypes.c_short]
usb_tc08_get_single.restype = ctypes.c_short

> now how i can use the function?
> leggo = strumento.usb_tc08_get_single(0, temp,
> 'NULL','USBTC08_UNITS_CENTIGRADE')

That's wrong too. In the C code, the third parameter is NULL - this  
corresponds to None in Python, not the string 'NULL'.
Also, they define a temporary float array of size 9 and use it as the  
second argument - we have to do the same in Python. (Note that ctypes  
accepts an array in place of a pointer argument, same as C).
Last, you have to search for the value of USBTC08_UNITS_CENTIGRADE, likely  
it's a #define in a .h header file. Suppose you find the corresponding  
value is 42:

USBTC08_UNITS_CENTIGRADE = 42
temp = (ctypes.c_float * 9)()
handle = 0
leggo = usb_tc08_get_single(handle, temp, None, USBTC08_UNITS_CENTIGRADE)

Hope it helps,
-- 
Gabriel Genellina




More information about the Python-list mailing list