# Process math.h # # (note: this requires py2.6, since that is when c_longdouble first appeared) # # Looking in math_c.py, we see some useful definitions, but not all # that much, yet... h2xml /usr/include/math.h -o math_c.xml xml2py math_c.xml -o math_c.py # Add the -c argument : include C preprocessor headers # # Now, we see a lot more defined in the math_c.py . For example, # M_PI, as defined in math.h, is included. h2xml /usr/include/math.h -c -o math_c.xml xml2py math_c.xml -o math_c.py # -l: auto-load a library # # When you pass the -l argument, it will scan the libary for # executable symbols. If it finds them, it will automatically set up # to run, using ctypes, from that library. In this example, math_c.py # becomes a module which automatically interface to libm h2xml /usr/include/math.h -c -o math_c.xml xml2py math_c.xml -o math_c.py -l /lib/libm.so.6 # In math_c.py: # # | _libraries['/lib/libm.so.6'] = CDLL('/lib/libm.so.6') # | # | log10 = _libraries['/lib/libm.so.6'].log10 # | log10.restype = c_double # | log10.argtypes = [c_double] # # which is an automatic ctypes interface to log10 in libm # To use it: python2.6 >>> import math_c >>> math_c.log10(100) 2.0 ######################################## # Let's play with time.h (works on python2.5): # # We get a lot of stuff, for example, the ctypes definition of the C # structure "struct tm" is automatically created, for example: # # | class tm(Structure): # | pass # | tm._fields_ = [ # | ('tm_sec', c_int), # | ('tm_min', c_int), # | ('tm_hour', c_int), # | ('tm_mday', c_int), # | ('tm_mon', c_int), # | ('tm_year', c_int), # | ('tm_wday', c_int), # | ('tm_yday', c_int), # | ('tm_isdst', c_int), # | ('tm_gmtoff', c_long), # | ('tm_zone', STRING), # | ] # # We also have various functions defined: # # | _libraries['/lib/libc.so.6'] = CDLL('/lib/libc.so.6') # | # | strptime = _libraries['/lib/libc.so.6'].strptime # | strptime.restype = STRING # | strptime.argtypes = [STRING, STRING, POINTER(tm)] # We use '-l /lib/libc.so.6', so that we automaticall set up to run # defined functions from libc.so.6, using ctypes h2xml /usr/include/time.h -o time_c.xml xml2py time_c.xml -o time_c.py -l /lib/libc.so.6 man strptime python >>> import time_c # Initialize a `struct tm` object to use as the return values of our # function call. >>> tm = time_c.tm() # Call strptime, with two strings and a pointer to the struct_tm. Read # the manual page on strptime to understand the return value. >>> time_c.strptime("Dec 19, 1985", "%b %d, %Y", tm) '' # And our data structure is filled in: >>> tm.tm_yday 352 >>> tm.tm_year 85 >>> tm.tm_wday 4 # In short, anything in a C header file, we can now do from Python # using ctypes, without having to define a ctypes interface manually.