Differences between revisions 3 and 4
Revision 3 as of 2007-07-13 17:16:43
Size: 1229
Editor: 209
Comment: add FAQ re change the byte length of a ctypes.Structure
Revision 4 as of 2007-07-13 17:18:05
Size: 1842
Editor: 209
Comment: add FAQs re transliterating memcpy offsetof uchar ((void *) -1)
Deletions are marked like this. Additions are marked like this.
Line 30: Line 30:

'''FAQ: How do I say memcpy?'''

memmove

'''FAQ: How do I say offsetof?'''

If the field is a member of an instance of a struct class or an array class, then:

def offsetof(self, field):
 return ctypes.addressof(field) - ctypes.addressof(self)

Otherwise you have to sum up the aligned sizes of the _fields_ that precede the fieldname. If _pack_ is 1, then the aligned size of each field is merely its ctypes.sizeof, otherwise you have to work harder.

'''FAQ: How do I say uchar?'''

ctypes.c_ubyte

'''FAQ: How do I say ((void *) -1)?'''

INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value

"ctypes is an advanced ["ffi"] ... package for Python ...", according to its [http://www.python.net/crew/theller/ctypes/ home page]. ["Python 2.5"] includes ctypes.

CTypes FAQs

FAQ: How do I copy bytes to Python from a ctypes.Structure?

def send(self):

  • return buffer(self)[:]

FAQ: How do I copy bytes to a ctypes.Structure from Python?

def receiveSome(self, bytes):

  • ctypes.memmove(ctypes.addressof(self), bytes, ctypes.sizeof(self))

FAQ: Why should I fear using ctypes.memmove?

ctypes.memmove emulates the memmove of C with complete faithfulness. If you tell memmove to copy more bytes than sizeof(self), you will overwrite memory that you do not own, with indeterminate consequences, arbitrarily delayed.

FAQ: How do I change the byte length of a ctypes.Structure?

Declare the max length and allocate that much memory, but then copy less than all of the memory allocated. You change the byte length that you use, not the byte length that ctypes.sizeof reports. For example:

class MaxByteString(ctypes.Structure):

  • _fields_ = [('Bytes'), 0xFF * ctypes.c_ubyte)]

Someone more Wiki literate than I should kill the false hot link at MaxByteString above.

FAQ: How do I say memcpy?

memmove

FAQ: How do I say offsetof?

If the field is a member of an instance of a struct class or an array class, then:

def offsetof(self, field):

  • return ctypes.addressof(field) - ctypes.addressof(self)

Otherwise you have to sum up the aligned sizes of the _fields_ that precede the fieldname. If _pack_ is 1, then the aligned size of each field is merely its ctypes.sizeof, otherwise you have to work harder.

FAQ: How do I say uchar?

ctypes.c_ubyte

FAQ: How do I say ((void *) -1)?

INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value

ctypes (last edited 2011-11-30 00:28:21 by webproxy3)

Unable to edit the page? See the FrontPage for instructions.