Converting arrarys in Python to arrays in C

Lonnie Princehouse fnord at u.washington.edu
Wed Dec 17 20:33:00 EST 2003


It doesn't look to me like Numeric does what you want to do;
it looks more like you want to print out C code that initializes
a big array.

Try writing a function that counts the number of dimensions 
you're working with:

import types  

# quick and dirty, assumes you've only got tuples and integers
def dimensions(obj):  
  if not isinstance(obj, types.TupleType):
    return 0
  else:
    return 1 + dimensions(obj[0]) 


# Now you don't need array0D, array1D, etc.. 

def write_array(data):
  dims = dimensions(data)
  print "unsigned char%s = " % "[]" * dims
  ...   

I've gotta run (no time to finish this post), but hopefully that helps...




Simon Foster <simon at uggs.demon.co.uk> wrote in message news:<3fe06b14$0$25662$cc9e4d1f at news.dial.pipex.com>...
> 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