Re: ctypes char array question

Thomas Heller <[email protected]> Fri, 02 Dec 2011 22:52:35 +0100
Newsgroups gmane.comp.python.ctypes
Message-ID <[email protected]>
Am 02.12.2011 18:32, schrieb Steve Thompson:
> There needs to be a method of accessing that information.  I can't force
> developers to modify their embedded source code or hack in a work around
> on the python side every time I generate ctypes from the embedded C
> code.  That's not a good long term solution.

You can add a property to the struct class that does automate the 
conversion for you:

<code>
# -*- coding: latin-1 -*-
from ctypes import *

class struct(Structure):
     _fields_ = [("_first", c_ubyte * 4),
                 ("second", c_int)]

     def _get(self):
         return "".join([chr(c) for c in self._first])
     def _set(self, text):
         self._first[:] = [ord(c) for c in text]
     first = property(_get, _set)

s = struct()
s.first = "ab\0c"

print (s._first, s.first)
</code>

which prints:

(<__main__.c_ubyte_Array_4 object at 0x02CCAA80>, 'ab\x00c')


>
> Any thoughts on if/when this could be added?  Is there no way to access
> the underlying raw data?

I don't maintain ctypes anymore.

Thomas


------------------------------------------------------------------------------
All the data continuously generated in your IT infrastructure 
contains a definitive record of customers, application performance, 
security threats, fraudulent activity, and more. Splunk takes this 
data and makes sense of it. IT sense. And common sense.
http://p.sf.net/sfu/splunk-novd2d