Converting arrarys in Python to arrays in C

Simon Foster simon at uggs.demon.co.uk
Wed Dec 17 09:41:24 EST 2003


I have some code which attempts to convert Python arrays (tuples of 
tuples of tuples...) etc. into C arrays with equivalent contents.

The prototype code is shown below.

My only question is, is there some way of doing this without repeating 
the try..except blocks ad-infinitum to handle 3D, 4D arrays etc.

I can see there is a pattern here but I can't seem to turn it into a 
loop.  Would a recursive solution do the trick?


cdata0 = 0

cdata1 = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 )

cdata2 = (( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ),
           ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ))

if __name__ == '__main__':

     import sys
     sys.stdout = file( 'cdata.log', 'w' )

     def arrayLine( s ):
         return ', '.join( [ '0x%04X' % t  for t in s ] )

     def array0D( data ):
         print 'unsigned char = 0x%04X;' % data

     def array1D( data ):
         print 'unsigned char[] = { %s };' % arrayLine( data )

     def array2D( data ):
         array = [ 'unsigned char[][] = {' ]
         for i in data:
             array.append( '\t{ %s },' % arrayLine( i ))
         array.append( '};' )
         print '\n'.join( array )

     for cdata in cdata0, cdata1, cdata2:
         declare = []
         try:
             iter(cdata)
             try:
                 iter(cdata[0])
                 try:
                     iter(cdata[0][0])
                 except TypeError:
                     array2D( cdata )
             except TypeError:
                 array1D( cdata )
         except TypeError:
             array0D( cdata )





More information about the Python-list mailing list