ctypes and byte order

Jean-Michel Pichavant jeanmichel at sequans.com
Thu Jun 18 05:39:55 EDT 2015


Hi list,

I'm currently writing python code that writes a small binary file to be used by another device which code is written in C.
The python code runs on a little endian CPU, and unfortunately, the other device is using a big endian MIPS.

My problem is the following: I cannot make an array of n int work in big endian, I can workaround the problem by creating n intergers, which is nicely done thanks to list comprehension but that seems to me like a misuse of the ctypes modules.

ctypes is expecting a 'c_uint_be_Array_5' (note the _be_ for big endian), and I don't know how to construct such object.

I hope I am clear.

Thanks,

JM

here's a code sample (python 2.7):

--------------------
import ctypes, sys

iarray = ctypes.c_uint32*5  # array of 5 unsigned 32 bits

class Foo(ctypes.Structure):
	"""Native byte order, won't work on my big endian device"""
	_fields_ = [('bar', iarray)] 

class Foo_be(ctypes.BigEndianStructure):
	"""big endian version, but python code fails"""
	_fields_ = [('bar', iarray)] 

class Foo_be_working(ctypes.BigEndianStructure):
	"""Working big endian version, looks more like a workaround."""
	_fields_ = [('bar%i'%i, ctypes.c_uint32) for i in range(5)]


print sys.version
f = Foo(iarray(0,1,2,3,4))
print "uint32 array: ", f.bar

f_be = Foo_be_working(0,1,2,3,4)
print "bar0 and bar5: ", f_be.bar0, f_be.bar5

f_be = Foo_be(iarray(0,1,2,3,4)) # will raise an exception

--------------------


The output

2.7.3 (default, Mar 13 2014, 11:03:55) 
[GCC 4.7.2]
uint32 array:  <__main__.c_uint_Array_5 object at 0x1cf4560>
bar0 and bar4:  0 4


TypeError: incompatible types, c_uint_Array_5 instance instead of c_uint_be_Array_5 instance
     24 
---> 25 f_be = Foo_be(iarray(0,1,2,3,4))
     26 



-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


More information about the Python-list mailing list