On Sep 13, 6:45 am, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> wrote: > On Sep 12, 6:38 pm, [EMAIL PROTECTED] wrote: > > > > > > > > > Hello! > > > I wanted to get the full contents of a character array stored in a > > struct, i.e. > > _fields_ = [...("array", c_char * 12)...] > > however,ctypesseems to try to return struct.array as a Python string > > rather than a character array, and stops as soon as it encounters a > > null within the character array. > > > I ended up having to define a dummy struct > > class dummystruct(Structure): > > _fields_ = [] > > > and declare array as: > > ("array", dummystruct) > > > then use string_at(byref(struct.array), 12). > > > Is this really the best way of doing it? Is there no better way to > > work aroundctypes'guess what you want' behaviour? > > > Thanks in advance, > > Rodrigo > > Rodrigo, > > If you have the option to change your declaration to c_byte* 12, you > have more options. This example prints the null character you wanted. > > fromctypesimport * > import struct > class S( Structure ): > _fields_= [ > ( 'array', c_byte* 12 ) > ] > s= S() > > #initialize > struct.pack_into( '7s', s.array, 0, 'abc\x00def' ) > > #prototype and call PyString_FromStringAndSize > prototype= PYFUNCTYPE( py_object, POINTER( c_byte ), c_size_t ) > PyString_FromStringAndSize= prototype( ( "PyString_FromStringAndSize", > pythonapi ) ) > x= PyString_FromStringAndSize( s.array, 12 ) > print repr( x ) > > #prototype and call PyString_FromString for contrast > prototype= PYFUNCTYPE( py_object, POINTER( c_byte ) ) > PyString_FromString= prototype( ( "PyString_FromString", pythonapi ) ) > x= PyString_FromString( s.array ) > print repr( x ) > > /Output: > > 'abc\x00def\x00\x00\x00\x00\x00' > 'abc'
Great - and thank you for replying so fast! I found that [chr(x) for x in struct.array] with array as a c_byte * 12 did what I needed. -- http://mail.python.org/mailman/listinfo/python-list