473,320 Members | 2,109 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Converting arrarys in Python to arrays in C

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 )

Jul 18 '05 #1
3 1807
Simon Foster <si***@uggs.demon.co.uk> wrote:
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?


Probably yes, but why reinvent the wheel? Numeric does what you want
already and allows for efficient conversions too [1].

Anton
[1] For example, using your code as a basis:

import Numeric

def test():
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 ))

for cdata in cdata0, cdata1, cdata2:
a = Numeric.array(cdata)
print a.shape
print a
print

if __name__=='__main__':
test()
Jul 18 '05 #2
Simon Foster wrote in message
<3f***********************@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.
This doesn't generate legal C.

It also does no bounds checking, so you may end up with a Python int that
doesn't fit into a C char. (Which is most certainly 1 byte, so why do you
use 4 hex digits to represent it?)
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.
Of course. This approach you used is in fact very unusual, especially with
the print statements. You've simply made a special purpose function for
each depth of array.
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?


The recursive solution is more natural here, I think, but iterative is
possible, too.

The pattern is ', '.join(<elements>), where <elements> is {<arrayORint>}.
The rest is just fluff.

You seem to have gotten hung up on the type declaration. You can't declare
the type until you know the depth of the array, so generate the array first,
*then* get construct the declaration.

Now for homework, convert the hackish solution below into a recursive
generator. ;)

def seqtobrace(seq, depth=0):
"""Return a comma- and brace-delimited version of seq, and the depth of
seq."""
depth += 1
if isinstance(seq[0], (tuple, list)):
subelem, depths = zip(*[seqtobrace(s, depth) for s in seq])
delim = ',\n' + ' '*2*depth
depth = depths[0]
elements = delim.join(subelem)
elif isinstance(seq[0], (int, long)):
elements = ', '.join(map(hex, seq))
else:
raise TypeError, "seq must be list or tuple with int or long
leaves."
return '{ %s }' % elements, depth

def toCarray(seq, name):
"""Return an unsigned char C array declaration of name from seq."""
assert isinstance(name, basestring)
if isinstance(seq, (int, long)):
return 'unsigned char %s = 0x%X;' % (name, seq)
else:
array, depth = seqtobrace(seq)
ad = '[]'*depth
typedec = 'unsigned char%s %s = \n' % (ad, name)
return typedec + array + ';'
--
Francis Avila

Jul 18 '05 #3
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 <si***@uggs.demon.co.uk> wrote in message news:<3f***********************@news.dial.pipex.co m>...
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 )

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: matt melton | last post by:
Hi there, I am trying to write a method that accepts an array of any primitive type and will return the same array without copying memory as an array of bytes. ie. I'd like to be able to do...
14
by: Sridhar R | last post by:
Consider the code below, class Base(object): pass class Derived(object): def __new__(cls, *args, **kwds): # some_factory returns an instance of Base # and I have to derive from this...
7
by: Tim Clacy | last post by:
I know arrays of references are not allowed, but have a couple of questions: 1) Why aren't arrays of references allowed :-) ? 2) What's a good practical alternative? As an example, Intel's...
1
by: Foxy Kav | last post by:
Hi everyone, im a first year UNI student doing a programming subject and im stuck on how to get rid of my global variables, char stringarray and char emptystring. I was wondering if anyone could...
4
by: Cyde Weys | last post by:
I'm currently working on converting a simulator program from Visual Basic 6.0 to Visual C++ .NET. I've figured out most of the stuff, but there's still one thing I haven't gotten to and I've never...
3
by: Pete Davis | last post by:
I've never done this in C# so I don't know what the appropriate way of doing it is. I've got an array of bytes and I need to convert the array into "usable" data. For example, the first 4 bytes...
11
by: efrat | last post by:
Hello, I'm planning to use Python in order to teach a DSA (data structures and algorithms) course in an academic institute. If you could help out with the following questions, I'd sure...
5
by: zefciu | last post by:
Hi! I want to embed a function in my python application, that creates a two-dimensional array of integers and passes it as a list (preferably a list of lists, but that is not necessary, as the...
156
by: Lame Duck | last post by:
Hi Group! I have a vector<floatvariable that I need to pass to a function, but the function takes a float * arguement. That's OK, I can convert by doing &MyVector.front(), but when I get back a...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.